Source: http://bailian.openjudge.cn/practice/4078/ 4078: Implementing the heap Structure
Total time limit: 1000ms memory limit: 65536kB
Description
Defines an array, initialized to null. Perform two operations on the array:
1, add 1 elements, put 1 new elements into the array.
2. Output and delete the smallest number in the array.
Efficient algorithm for implementing the above functions using the heap structure.
input
The first line enters an integer n, which represents the number of operations.
Each operation first enters an integer type.
When type=1, add an action, and then enter an integer u that represents the element to be inserted.
When type=2, outputs the delete operation, outputting and deleting the smallest element in the array.
1<=n<=100000.
Output
Each delete operation outputs the number that was deleted.
Sample Input
4
1 5
1 1
1 7
2
Sample Output
1
Tips
The complexity of each set of test data is O (NLOGN) algorithm to pass this time, otherwise it will return Tle (timeout)
Need to use minimal heap structure to implement the algorithm
-----------------------------------------------------
Thinking of solving problems
Minimum heap, with priority_queue< int, vector<int>, greater<int> > implementation.
Required header Files
#include <queue>
#include <vector>
#include <functional>//Std::greater
Build a heap
priority_queue< int, vector<int>, greater<int> > heap; Minimum heap: Build priority queue with Std::greater
element into the heap
Heap.push (Openum);
Take the top element of the heap
cout << heap.top () << Endl;
Heap top element out of heap
Heap.pop ();
-----------------------------------------------------
Code
#include <iostream> #include <fstream> #include <queue> #include <vector> #include <
Functional> using namespace std;
int main () {#ifndef Online_judge ifstream fin ("xly2017GG.txt");
int N, J, Opecode, Openum; priority_queue< int, vector<int>, greater<int> > heap;
Minimum heap: Build a priority queue with 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_judge int N, J, Opecode, Openum; priority_queue< int, vector<int>, greater<int> > heap;
Minimum heap: Build priority queue cin >> n with Std::greater;
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}