消息队列是Windows系统的基础。对于每个进程,系统维护一个消息队列。如果在进程中有特定事件发生,如点击鼠标、文字改变等,系统将把这个消息加到队列当中。同时,如果队列不是空的,这一进程循环地从队列中按照优先级获取消息。请注意优先级值低意味着优先级高。请编辑程序模拟消息队列,将消息加到队列中以及从队列中获取消息。
输入格式:
输入首先给出正整数N(≤105),随后N行,每行给出一个指令——GET
或PUT
,分别表示从队列中取出消息或将消息添加到队列中。如果指令是PUT
,后面就有一个消息名称、以及一个正整数表示消息的优先级,此数越小表示优先级越高。消息名称是长度不超过10个字符且不含空格的字符串;题目保证队列中消息的优先级无重复,且输入至少有一个GET
。
输出格式:
对于每个GET
指令,在一行中输出消息队列中优先级最高的消息的名称和参数。如果消息队列中没有消息,输出EMPTY QUEUE!
。对于PUT
指令则没有输出。
输入样例:
9
PUT msg1 5
PUT msg2 4
GET
PUT msg3 2
PUT msg4 4
GET
GET
GET
GET
输出样例:
msg2
msg3
msg4
msg1
EMPTY QUEUE!
解题思路:
这道题一开始想的是用 map<int, string>queue 来记录,然后每次输出queue.begin()就行了,后来发现超时了,百度了一下发现要用优先队列,然后对运算符重载一下变成从小到大排序
超时版本
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <map>
#include <iostream>
using namespace std;
map<int, string> queue; //消息队列
map<int, string>::iterator it;
int main(){
int n;
scanf("%d", &n);
string ins;
string name;
int pri;
for(int i=0; i<n; i++){
cin >> ins; //输入指令
if(ins == "PUT"){
cin >> name;
cin >> pri;
//题目说了优先级不会重复,所以不需要判断
queue[pri] = name;
} else if(ins == "GET"){
if(queue.empty()){ //空队列
printf("EMPTY QUEUE!\n");
continue;
}
it = queue.begin();
printf("%s\n", it->second.c_str());
queue.erase(it->first); //删除元素
}
}
return 0;
}
抄别人的AC版本
#include<stdio.h>
#include<queue>
#include<vector>
using namespace std;
struct node{
char s[15];
int rank;
friend bool operator < (node a,node b ){ //运算符重载,返回1则交换位置,返回0则不交换
return a.rank>b.rank; //最后是从小到大排序
}
};
priority_queue<node> q;
int main(){
int n,i;
char s[5],message[15];
node temp;
scanf("%d",&n);
getchar();
for(i=0;i<n;i++){
scanf("%s",&temp.s);
if(temp.s[0]=='G'){
if(q.size()==0){
printf("EMPTY QUEUE!\n");
}
else{
node a=q.top();
q.pop();
printf("%s\n",a.s);
}
}
else{
scanf("%s %d",temp.s,&temp.rank);
q.push(temp);
}
}
return 0;
}