</pre><pre name="code" class="cpp">#include <iostream>
#include <algorithm>
using namespace std;
typedef int T;
const int MAXSIZE = 1000;
struct MinHeap{
T heap[MAXSIZE];
int sz;
MinHeap(){ sz = 0; }
int size(){return sz; }
bool empty(){ return sz==0; }
void push(T val){
heap[sz] = val;
int pa = sz/2, cur = sz;
while(cur>0 && heap[pa] > heap[cur]){ //push_up
swap(heap[pa], heap[cur]);
cur = pa;
pa = cur/2;
}
sz++;
}
void pop(){
if(empty()) return;
heap[0] = heap[--sz];
int tmp, tx, cur=0, lchild, rchild;
while(cur < sz){
lchild = 2*cur, rchild = 2*cur+1;
tmp = heap[cur], tx = cur;
if(lchild < sz && heap[lchild] < tmp) tmp = heap[lchild], tx = lchild;
if(rchild < sz && heap[rchild] < tmp) tmp = heap[rchild], tx = rchild;
if(tx == cur) break; //如果孩子都比自己大,则退出
swap(heap[tx], heap[cur]);
cur = tx;
}
}
T top(){
if(empty()) return -1;
return heap[0];
}
};
堆模板,自家用
最新推荐文章于 2023-08-06 18:38:14 发布