STL
#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
struct node
{
char s[100];
int pri,idx;
friend bool operator <(node a,node b){
return a.pri>b.pri;
}
};
int main()
{
char str[1000];
priority_queue<node> q;
while(scanf("%s",str)!=EOF){
if(strcmp(str,"GET")==0){
if(q.empty())
printf("EMPTY QUEUE!\n");
else{
node tmp=q.top();
q.pop();
printf("%s %d\n",tmp.s,tmp.idx);
}
}
else if(strcmp(str,"PUT")==0){
char ss[100];
int p;int x;
scanf("%s%d%d",ss,&p,&x);
node tmp;
strcpy(tmp.s,ss);
tmp.idx=p;
tmp.pri=x;
q.push(tmp);
}
}
return 0;
}
二叉树
#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=60000+10;
const int maxs=100;
struct info
{
char name[maxs];
int para; //参数
int pri,t; //优先级,顺序。
}p[maxn];
int heap[maxn];
int top,used;
int compare(int a,int b)
{
if(p[a].pri<p[b].pri)
return -1;
if(p[a].pri>p[b].pri)
return 1;
if(p[a].t>p[b].t)
return 1;
if(p[a].t<p[b].t)
return -1;
return 0;
}
int main()
{
int used=0,top=0;
int cnt=0;
char str[1000];
while(scanf("%s",str)!=EOF){
if(strcmp(str,"GET")==0){
if(top){
printf("%s %d\n",p[heap[1]].name,p[heap[1]].para);
int k=1;
heap[k]=heap[top--];
while(k*2<=top){
int t=2*k;
if(t<top&&compare(heap[t],heap[t+1])>0)
t++;
if(compare(heap[k],heap[t])>0){
swap(heap[k],heap[t]);
k=t;
}else
break;
}
}
else
printf("EMPTY QUEUE!\n");
}else{
scanf("%s%d%d",p[used].name,&p[used].para,&p[used].pri);
p[used].t=cnt++;
int k=++top;
heap[k]=used++;
while(k>1){ //从下往上建堆。
int t=k/2;
if(compare(heap[k],heap[t])<0){
swap(heap[k],heap[t]);
k=t;
}
else
break;
}
}
}
return 0;
}