本文地址: http://blog.csdn.net/caroline_wendy
堆(heap)作为二叉树的重要应用, 时间复杂度O(logn), 需要熟练的写出其代码, 基本代码如下, 需要背写.
代码:
/*
* main.cpp
*
* Created on: 2014.7.20
* Author: spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <stdio.h>
class Heap {
static const int MAX_N = 1000;
int heap[MAX_N], sz=0;
public:
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 a=i*2+1, b=i*2+2;
if (b<sz && heap[b]<heap[a]) a=b; //a始终代表最小值
if (heap[a]>=x) break;
heap[i] = heap[a];
i = a;
}
heap[i] = x;
return ret;
}
};
int main(void)
{
Heap h;
h.push(3);
h.push(5);
h.push(4);
h.push(1);
for (int i=0; i<4; ++i) {
printf("%d ", h.pop());
}
printf("\n");
return 0;
}
1 3 4 5
也可以使用库函数(#include<queue>)的优先级队列(priority_queue), 但是取值默认得到最大值,
可以使用priority_queue<int, vector<int>, greater<int> > 输出最小值.
代码:
/*
* main.cpp
*
* Created on: 2014.7.20
* Author: spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <stdio.h>
#include <queue>
#include <vector>
#include <functional>
using namespace std;
int main(void)
{
priority_queue<int, std::vector<int>, std::greater<int> > pque;
pque.push(3);
pque.push(5);
pque.push(1);
pque.push(4);
while (!pque.empty()) {
printf("%d ", pque.top());
pque.pop();
}
printf("\n");
return 0;
}
1 3 4 5
原文:http://blog.csdn.net/caroline_wendy/article/details/38010101