堆的基本模板
int heap[MAX_N],sz = 0;
void push(int x){
// 自己结点的编号
int i = sz ++;
while (i > 0){
// 父亲结点的编号
int p = (i-1)/2;
// 如果已经没有大小颠倒则退出
if (heap[p] <= x) break;
// 把父亲结点的数值放下来,而把自己提上去
heap[i] = heap[p];
i = p;
}
heap[i] = x;
}
int pop() {
// 最小值
int ret = heap[0];
// 要提到根的数值
int x = heap[--sz];
// 从根开始向下交换
int i = 0;
while (i*2 + 1 < sz){
// 比较儿子的值
int lson = i*2 + 1,rson = i*2 + 2;
if (rson < sz && heap[rson] < heap[lson]) lson = rson;
// 如果已经没有大小颠倒则退出
if (heap[lson] >= x)break;
// 把儿子的数值提上来
heap[i] = heap[lson];
i = lson;
}
heap[i] = x;
return ret;
}
附上大神STL的链接:
点击打开链接