題目來源:http://bailian.openjudge.cn/practice/4078/ 4078:實現堆結構
總時間限制: 1000ms 記憶體限制: 65536kB
描述
定義一個數組,初始化為空白。在數組上執行兩種操作:
1、增添1個元素,把1個新的元素放入數組。
2、輸出並刪除數組中最小的數。
使用堆結構實現上述功能的高效演算法。
輸入
第一行輸入一個整數n,代表操作的次數。
每次操作首先輸入一個整數type。
當type=1,增添操作,接著輸入一個整數u,代表要插入的元素。
當type=2,輸出刪除操作,輸出並刪除數組中最小的元素。
1<=n<=100000。
輸出
每次刪除操作輸出被刪除的數字。
範例輸入
4
1 5
1 1
1 7
2
範例輸出
1
提示
每組測試資料的複雜度為O(nlogn)的演算法才能通過本次,否則會返回TLE(逾時)
需要使用最小堆結構來實現本題的演算法
-----------------------------------------------------
解題思路
最小堆,用priority_queue< int, vector<int>, greater<int> >實現。
需要的標頭檔
#include<queue>#include<vector>#include<functional> // std::greater
建堆
priority_queue< int, vector<int>, greater<int> > heap;// 最小堆:用std::greater構建優先隊列
元素入堆
heap.push(openum);
取堆頂元素
cout << heap.top() << endl;
堆頂元素出堆
heap.pop();
-----------------------------------------------------
代碼
#include<iostream>#include<fstream>#include<queue>#include<vector>#include<functional>using namespace std;int main(){#ifndef ONLINE_JUDGEifstream fin("xly2017GG.txt");int n, j, opecode, openum;priority_queue< int, vector<int>, greater<int> > heap;// 最小堆:用std::greater構建優先隊列fin >> n;for (j=0; j<n; j++){fin >> opecode;if (opecode == 1){fin >> openum;heap.push(openum);}else if(opecode == 2){cout << heap.top() << endl;heap.pop();}}fin.close();#endif#ifdef ONLINE_JUDGEint n, j, opecode, openum;priority_queue< int, vector<int>, greater<int> > heap;// 最小堆:用std::greater構建優先隊列cin >> n;for (j=0; j<n; j++){cin >> opecode;if (opecode == 1){cin >> openum;heap.push(openum);}else if(opecode == 2){cout << heap.top() << endl;heap.pop();}}#endif}