题目链接:http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_9_C
结合上一题的最大堆,实现优先队列的功能:
insert:插入元素
extract:就是pop出顶端元素,即返回当前的最大元素并且删除它的功能。
插入:把元素往最后插,然后向上层遍历,寻找到正确的位置为止。(因为假设当前的堆已经是最大堆)
删除:把A[1]的元素pop,然后删除的过程就是把最后一个元素放到第一个,然后对顶端元素执行max_heap操作,就保证了顶端元素的正确,而且把最后一个元素的位置也找到了。
代码如下:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define infinity (1<<30)
const int maxx=2000100;
int A[maxx];
int n;
void max_heap(int i){
int left=2*i,right=2*i+1,x;
if(left<=n && A[left]>A[i]) x=left;
else x=i;
if(right<=n && A[right]>A[x] ) x=right;
if(x!=i){
swap(A[x],A[i]);
max_heap(x);
}
return ;
}
int extract(){
int x;
x=A[1];
A[1]=A[n];
n--;
max_heap(1);
return x;
}
int main (){
string s;
int a;
n=0;
while(cin>>s){
if(s[0]=='i'){
cin>>A[++n];
int i=n;
while(i>1 && A[i]>A[i/2]){
swap(A[i],A[i/2]);
i=i/2;
}
}
else if(s[1]=='x'){
cout<<extract()<<endl;
}
else return 0;
}
return 0;
}
错点:
1.这题对时间复杂度有一定要求,插入随便插,extract的时候再执行全堆的max_heap会TLE;
2.插入过程中i的值要注意+1的地方;
用STL中的priority_queue来实现
代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
int main (){
priority_queue<int> A;
string s;
int a;
while(cin>>s){
if(s[0]=='i') {
cin>>a;
A.push(a);
}
else if(s[1]=='x'){
a=A.top();
A.pop();
cout<<a<<endl;
}
else return 0;
}
return 0;
}