题目连接:
http://acm.hdu.edu.cn/showproblem.php?pid=1509
题目意思:
模拟计算机信息的处理,优先队列,输入put 放置信息,信息含有优先级,输出get ,根据优先级和队列特点。
题目算法:
使用堆,根据优先级和进队顺序建堆。堆顶是优先级最大,且最较先进队的。
和上次堆排的题目类似,但是多了个优先级,值得注意的是,进队的num保存是不随堆大小的,而是随总的队长(包括已经出对的)
因为在出对的时候,堆长度要减1,因此进队的那个就不能跟着堆长。
另外,down的时候,要比较左右子节点的,这是与up不同的地方。
ac代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n=0;
int count=0;
char str[4],get[]="GET";
struct node{
char name[1000];
int data;
int pri;
int num;
}queue[60000+24];
bool cmp(int a,int b){
if(queue[a].pri==queue[b].pri)
return queue[a].num < queue[b].num;
return queue[a].pri < queue[b].pri;
}
void swap(int a,int b){
node temp;
temp = queue[a]; queue[a] = queue[b]; queue[b] = temp;
}
void up(int c)
{
if(c==1)return;
if(cmp(c,c/2)){
swap(c,c/2);
up(c/2);
}
}
void insert()
{
++n;
++count;
scanf("%s%d%d",queue[n].name,&queue[n].data,&queue[n].pri);
queue[n].num=count;
up(n);
}
void down(int c)
{
int k=2*c;
if(k>n)return;
if(k+1<=n && cmp(k+1,k))k++;
if(cmp(k,c))
{
swap(k,c);
down(k);
}
}
void pop()
{
if(n==0)printf("EMPTY QUEUE!\n");
else{
printf("%s %d\n",queue[1].name,queue[1].data);
swap(1,n--);
down(1);
}
}
int main()
{
//freopen("1509.txt","r",stdin);
while(~scanf("%s",str))
{
if(strcmp(str,get)==0)pop();
else{
insert();
}
}
return 0;
}