练习题 No.13 最小堆

来源:互联网 发布:北京阿里云公司在哪 编辑:程序博客网 时间:2024/06/04 18:47

要求

连续输入n个数,每次输出当前数列中的最小值

限制条件

  • 1 <= n <= 10000

输入格式

第一行输入n
接着连续输入n行

输出格式

输出n行,每行为当前数列的最小值

测试输入

5
3
4
5
2
1

测试输出

3
3
3
2
1

解题思路

用数组来存最小堆。
右儿子的编号为自己的编号*2 + 1
左儿子的编号为自己的编号*2 + 2

代码

#include <iostream>using namespace std;  template<class T> class MyPriorityQueue {    private:         T heap[10001];        int size;    public:        MyPriorityQueue() {            size = 0;        }        void push(T x) {            int i = size++;            while (i > 0) {                int p = (i - 1) / 2;                if (heap[p] <= x) {                    break;                }                heap[i] = heap[p];                i = p;            }            heap[i] = x;        }        T pop() {            T ret = heap[0];            T x = heap[--size];            int i = 0;            while (i * 2 + 1 < size) {                int left = i * 2 + 1;                int right = i * 2 + 2;                if (right < size && heap[right] < heap[left]) {                    left = right;                }                if (heap[left] >= x) {                    break;                }                heap[i] = heap[left];                i = left;            }            heap[i] = x;            return ret;        }        T top() {            return heap[0];        }}; int main() {    MyPriorityQueue<int> q;    int n;    cin >> n;    for (int i = 0; i < n; i++) {        int temp;        cin >> temp;        q.push(temp);        cout << q.top() << endl;    }    return 0;  }
0 0