最小堆建立

2021-07-10 08:35:32 字數 1879 閱讀 1109

題目:實現最小堆兩個功能:

1、增加乙個元素

2、輸出並刪除最小堆中的最小的數

輸入:

第一行輸入乙個整數t,代表測試資料的組數。

對於每組測試資料,第一行輸入乙個整數n,代表操作的次數。

每次操作首先輸入乙個整數type。

當type=1,增添操作,接著輸入乙個整數u,代表要插入的元素。

當type=2,輸出刪除操作,輸出並刪除陣列中最小的元素。

1<=n<=100000。

輸出 每次刪除操作輸出被刪除的數字。

樣例輸入

2

51 1

1 21 322

41 5

1 11 7

2

樣例輸出

1

21

解題思路:建立最小堆最終要的就是元素的插入與刪除。每插入乙個元素要確定元素要插入的位置,確定是向上篩還是向下篩。沒刪除乙個元素要將最後乙個元素放到跟的位置,然後進行向下篩的操作。

**片:

#include

using

namespace

std;

template

class minheap//析構函式

/*bool isleaf(int pos)const//如果是葉節點,返回true

*/int leftchild(int pos)const

//返回左孩子的位置

int rightchild(int pos)const

//返回右孩子的位置

int parent(int pos)const

//返回父節點的位置

bool remove(int pos, t& node);//刪除給定下標的元素

bool insert(const t& newnode);//向堆中插入新元素newnode

bool removemin(t& node); //堆中刪除最小元素

void siftup(int position);//從position開始向上調整

void siftdown(int left);//篩選法函式,引數left表示開始處理的陣列下標

};/*template minheap::minheap(t* h,int c=0,int m=100000 )*/

template

minheap::minheap(int n, int c, int m)

template

void minheap::buildheap()

template

void minheap::siftup(int position)

heaparray[pos] = temp;

}template

void minheap::siftdown(int left)

else

break;

}heaparray[i] = temp;

}template

bool minheap::remove(int pos, t& node)

template

bool minheap::insert(const t& newnode)

template

bool minheap::removemin(t& node)

int main()

else }}

return

0;}

總結:

最小堆怎麼建立

有乙個面試題,100w個數中找到最大的100個數。解決方式是,用乙個100個容量的最小堆,這100個數總數目前已知的最大的100個,而且 堆頂是小的,在繼續遍歷時候,只和堆定比較,如果這個數,比堆頂的大,就把這個數加入 這個堆。當遍歷完成後,這個最小堆中的數,就是最大的100個數了。當理解了這個,我...

用priority queue建立最小堆

標準庫里的priority queue預設建立的是最大堆,要建立最小堆的話,需要下面的形式。1 priority queue,greater minheap 最小堆2 priority queue,less maxheap 最大堆預設的就是最大堆,可以直接像下面那樣寫 priority queue ...

matlab建立最小堆演算法實現

最小堆是一顆完全二叉樹,他的每乙個節點的值不大於其左右子節點的值。leaf name a b c d e f g h leaf data 10,1,1,11,1,1,8,5 my heap heap my heap.min heap create leaf name,leaf data 函式定義如下...