标签:heap
几个概念:
堆的代码实现(数组实现):
int heap[10000], sz = 0;
void push(int x) { //向堆里面增加元素X
int i = sz++, p;
while(i > 0) {
p = (i - 1) / 2;
if(x >= heap[p]) break;
heap[i] = heap[p];
i = p;
}
heap[i] = x;
return;
}
int pop(void) { //弹出堆中最小(根元素),并返回该元素的值
int ret = heap[0];
int x = heap[--sz], i = 0;
while(i * 2 + 1 < sz) {
int l = i * 2 + 1, r = i * 2 + 2;
if(r < sz && heap[r] < heap[l]) l = r;
if(heap[l] >= x) break;
heap[i] = heap[l];
i = l;
}
heap[i] = x;
return ret;
}
标签:heap
原文地址:http://blog.csdn.net/jibancanyang/article/details/45100627