/* 挑战程序设计竞赛——第2版 P73 */ #include<iostream> #include<queue> #include<cstdio> #define MAX_N 100 using namespace std; 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 a = i * 2 + 1, b = i * 2 + 2; if (b < sz&&heap[b] < heap[a])a = b; if (heap[a] >= x)break; heap[i] = heap[a]; i = a; } heap[i] = x; return ret; } int main() { priority_queue<int> pque; pque.push(3); pque.push(5); pque.push(1); while (!pque.empty()) { cout << pque.top() << endl; pque.pop(); } system("pause"); return 0; }