Windows消息队列(25 分)
关键字:priority_queue实现优先队列(堆)
消息队列是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!
思路
priority_queue的基本使用:http://www.cnblogs.com/summerRQ/articles/2470130.html
按照题目要求重载运算符<,根据level优先级进行排序。order为PUT时入队,GET时出队,队为空时输出对应语句。要注意题目的超时问题,无论是message还是order,使用string会超时。
AC代码
/*
Name:7-4 Windows消息队列(25 分)
Author: shou1651312
Date:2017年10月23日 21:43:12
Description:数据结构实验3-1
ref:
priority_queue:http://www.cnblogs.com/summerRQ/articles/2470130.html
*/
#include<iostream>
#include<cmath>
#include<string>
#include<cstring>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<numeric>
#include<stack>
#include<queue>
using namespace::std;
struct node
{
char message[12];
int level;
bool operator <(const node &a) const
{
return level>a.level;
}
};
int main()
{
priority_queue<node> Q;
int N;
scanf("%d",&N);
for(int i=0; i<N; i++)
{
char order[5];
scanf("%s",order);
if(!strcmp(order,"PUT"))
{
node input;
scanf("%s%d",input.message,&input.level);
Q.push(input);
}
else if(!strcmp(order,"GET"))
{
if(!Q.empty())
{
printf("%s\n",Q.top().message);
Q.pop();
}
else
printf("EMPTY QUEUE!\n");
}
}
return 0;
}