百練 / 2017電腦學科夏令營上機考試: G(最小堆)

來源:互聯網
上載者:User

題目來源: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}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.