ZOJ 2724 Windows Message Queue (优先级队列,水题,自己动手写了个最小堆)

时间:2021-10-01 11:21:27
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm> using namespace std;
const int maxn=+;
int heap_size=; //堆的元素个数
struct Node{
char name[];
int para,pri;
int t; //用于存储信息加入的顺序,当优先级相同时,t小的先出队列
}node[maxn]; //交换node[a]和node[b]的值
void exchange(int a,int b){
Node tmp;
tmp=node[a];
node[a]=node[b];
node[b]=tmp;
}
//比较node[a]和node[b],若a小于,则返回-1。
int compare(int a,int b){
if(node[a].pri<node[b].pri)
return -;
if(node[a].pri>node[b].pri)
return ;
if(node[a].t<node[b].t)
return -;
if(node[a].t>node[b].t)
return ;
return ;
}
//维护堆,使堆保持最小堆的性质
void heap_update(int i){
int small;
int l=*i;
int r=*i+;
if(l<=heap_size && compare(l,i)<)
small=l;
else
small=i;
if(r<=heap_size && compare(r,small)<)
small=r;
if(small!=i){
exchange(i,small);
heap_update(small);
}
}
//加入一个新元素
void heap_insert(char str[],int para,int pri){
heap_size++;
strcpy(node[heap_size].name,str);
node[heap_size].para=para;
node[heap_size].pri=pri;
node[heap_size].t=heap_size;
int t=heap_size;
while(t> && node[t/].pri>node[t].pri){
exchange(t/,t);
t=t>>;
}
}
//将堆顶元素出队列
Node heap_pop(){
Node tmp=node[];
node[]=node[heap_size];
heap_size--;
heap_update();
return tmp;
}
int main()
{
char str[],s[];
Node tmp;
int para,pri;
while(scanf("%s",str)!=EOF){
if(str[]=='G'){
if(heap_size==){
printf("EMPTY QUEUE!\n");
}
else{
tmp=heap_pop();
printf("%s %d\n",tmp.name,tmp.para);
}
}
else{
scanf("%s%d%d",s,&para,&pri);
heap_insert(s,para,pri);
}
}
return ;
}