堆(模板)
小頂堆:
根節點比左右孩子都小
大頂堆:
根節點比左右兒子都大
小頂堆代碼:
#include <bits/stdc++.h> using namespace std; const int N = 1e6+5; template <typename T> class Heap { private:int heap[N];int sz; //heap size public://min heapHeap(){sz = 0;}void push(T val);void pop();T top(){return heap[1];}bool empty(){return sz==0;}int size(){return sz;}; };template<typename T> void Heap<T>::push(T val) {heap[++sz] = val;int cur = sz;//while cur isn't rootwhile(cur > 1){//不斷向上調整int rt = cur >> 1;if(heap[cur] < heap[rt]){swap(heap[cur],heap[rt]);cur = rt;}elsebreak;} }template<typename T> void Heap<T>::pop() {heap[1] = heap[sz--];//將最后一個元素放到堆頂int rt = 1;while(2*rt <= sz) //不是葉子節點{//find min son to swap//不斷向下調整int lson = rt<<1,rson = rt<<1|1;if(rson > sz || heap[rson] > heap[lson]) //rson>sz:without rson{if(heap[rt] > heap[lson]){swap(heap[rt],heap[lson]);rt = lson;}else break;}else{if(heap[rt] > heap[rson]){swap(heap[rt],heap[rson]);rt = rson;}else break;}} }int main() {int n;scanf("%d",&n);Heap<int> h;while(n--){int op,x;scanf("%d",&op);switch(op){case 1:scanf("%d",&x),h.push(x);break;case 2:printf("%d\n",h.top());break;case 3:h.pop();break;}}return 0; }總結
- 上一篇: P1433 吃奶酪(状压dp)
- 下一篇: ceil和floor