写了一个最大堆~
题目链接:
点击打开链接
代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
const int maxn = 100005;
struct Priority_queue{
int tot;
Priority_queue(int a){tot = a;}
int heap[maxn];
void Push(int num){
heap[tot] = num;
push_up();
tot++;
}
void push_up(){
int fa = tot/2;
int cur = tot;
while(heap[fa]<heap[cur]){
if(cur == 1) break;
swap(heap[fa],heap[cur]);
cur = fa;
fa = cur/2;
}
}
int Top(){
return heap[1];
}
void Pop(){
tot--;
heap[1] = heap[tot];
push_down(1);
}
void push_down(int root){
int l = root*2;
int r = root*2+1;
if(l>=tot){
return;
}
if(r>=tot){
if(heap[l]>heap[root]){
swap(heap[l],heap[root]);
}
return;
}
if(heap[l]>heap[r]){
if(heap[l]>heap[root]){
swap(heap[l],heap[root]);
push_down(l);
}
else return;
}else {
if(heap[r]>heap[root]){
swap(heap[r],heap[root]);
push_down(r);
}
else return;
}
}
};
int main(){
int n,x;
char ch;
scanf("%d",&n);
Priority_queue pq(1);
while(n--){
getchar();
scanf("%c",&ch);
if(ch == 'A'){
scanf("%d",&x);
pq.Push(x);
} else if(ch == 'T'){
printf("%d\n",pq.Top());
pq.Pop();
}
}
return 0;
}
思想:题目中的链接里讲了。
用stl的代码:
#include<iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
#include <cmath>
#include <map>
using namespace std;
priority_queue<int,vector<int>,less<int> > pq;
int main(){
int n,x;
char ch;
scanf("%d",&n);
while(n--){
getchar();
scanf("%c",&ch);
if(ch == 'A'){
scanf("%d",&x);
pq.push(x);
} else if(ch == 'T'){
printf("%d\n",pq.top());
pq.pop();
}
}
return 0;
}