ZOJ 2724 Windows Message Queue(优先队列)
题目链接: ZOJ 2724
| Describe: |
| Message queue is the basic fundamental of windows system. For each process, the system maintains a message queue. If something happens to this process, such as mouse click, text change, the system will add a message to the queue. Meanwhile, the process will do a loop for getting message from the queue according to the priority value if it is not empty. Note that the less priority value means the higher priority. In this problem, you are asked to simulate the message queue for putting messages to and getting message from the message queue. |
| Input: |
| There's only one test case in the input. Each line is a command, "GET" or "PUT", which means getting message or putting message. If the command is "PUT", there're one string means the message name and two integer means the parameter and priority followed by. There will be at most 60000 command. Note that one message can appear twice or more and if two messages have the same priority, the one comes first will be processed first.(i.e., FIFO for the same priority.) Process to the end-of-file. |
| Output: |
| For each "GET" command, output the command getting from the message queue with the name and parameter in one line. If there's no message in the queue, output "EMPTY QUEUE!". There's no output for "PUT" command. |
| Sample Input: |
| GET PUT msg1 10 5 PUT msg2 10 4 GET GET GET |
| Sample Output: |
| EMPTY QUEUE! msg2 10 msg1 10 EMPTY QUEUE! |
题目大意:
给若干个消息及其优先级,GET命令取出一个命令,若命令为空,输出EMPTY QUEUE! 相同优先级输出先进来的那个消息。
解题思路:
优先队列,构造一个结构体来存储数据,结构体中time来记录进来的顺序,注意比较函数。
AC代码:
1 #include <queue> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <iostream> 5 #define N 6e4+5 6 using namespace std; 7 struct node 8 { 9 char s[1005]; // 消息名称 10 int can,id,time; // 存储信息id,以及进入顺序 11 bool operator < (const node &a) const // 结构体内嵌比较函数 12 { 13 if(id == a.id) 14 return time>a.time; 15 return id>a.id; 16 } 17 }num; 18 int main() 19 { 20 priority_queue<node> q; 21 char t[5]; 22 int cas = 1; // 计数器,记录进入顺序 23 while(scanf("%s",t) != EOF) 24 { 25 if(t[0] == 'G') // 输出 26 { 27 if(q.empty()) 28 printf("EMPTY QUEUE!\n"); 29 else {node tmp = q.top(); q.pop(); printf("%s %d\n",tmp.s,tmp.can);} 30 } else if(t[0] == 'P') { // 输入消息 31 scanf("%s",num.s); 32 scanf("%d%d",&num.can,&num.id); 33 num.time = cas++; 34 q.push(num); 35 } 36 } 37 return 0; 38 }

浙公网安备 33010602011771号