標籤:優先隊列 c++容器
連結:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2724
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
GETPUT msg1 10 5PUT msg2 10 4GETGETGET
Sample Output
EMPTY QUEUE!msg2 10msg1 10EMPTY QUEUE!
翻譯:訊息佇列是Windows作業系統的基石,對於每一個進程,系統維持了一個訊息佇列,如果一個進程發生了某一事件,如單擊滑鼠,文本改變,系統將增加一個訊息到隊列裡,同時,如果隊列裡不是空的,那麼,進程將一直迴圈的從隊列裡按優先值抓取訊息,注意,數值小意味著高的優先順序,在本題中,要求你類比訊息佇列,把訊息放到訊息佇列中,或從訊息佇列裡抓取訊息;輸入描述:只有一個測試案例,每行是一條命令,“GET”或“PUT”表示從訊息佇列裡抓取訊息或把訊息放入訊息佇列。如果是“PUT”命令,後面跟著一個字串(表示訊息名稱)和兩個整數(分別表示訊息的參數和優先順序),案例中的命令最多達60000條,注意,一條命令可以重複出現多次,如果兩條命令的優先順序相同,則先進入訊息佇列的那條先被處理;一直處理到檔案結尾;輸出描述:對於每條“GET”指令,直接輸出他抓取的訊息的名稱和參數在一行上,如果訊息佇列是空的,那麼直接輸出“EMPTY QUEUE!”,對於“PUT”指令,不需要輸出什麼;
解題思路:本題是類比Windows處理訊息佇列,很有意義,解題中主要遇到的問題是逾時錯誤,根據本題的特點,宜使用優先隊列容器來實現;另外,光是用優先隊列容器還不行,必須採用scanf和printf輸入輸出,否則還會逾時,因為本題的資料量大,多達60000行字串需要處理,需要輸入輸出;
代碼:
#include <iostream>#include <cstdio>#include <queue>#include <cstdlib>#include <cstring>using namespace std;struct Message { //這裡不要用typedef了,因為重載運算子參數類型Message不能識別; char Name[200]; int data, priority; bool operator < (const Message a) const //重載 < 運算子自訂排序準則; { return a.priority < priority; }};int main(){ priority_queue <Message> v; //定義一個優先隊列的對象; char command[200]; while(~scanf("%s", command)) { //輸入命令; Message message; if(strcmp(command, "GET") == 0) { if(v.size() == 0) { //隊列為空白; printf("EMPTY QUEUE!\n"); //使用cout<<"EMPTY QUEUE"<<endl;不會逾時; }else { printf("%s %d\n", v.top().Name, v.top().data); //使用cout<<v.top().Name<<v.top().data會逾時; v.pop(); //出隊列操作,即將當前訊息清除; } }else if(strcmp(command, "PUT") == 0) { scanf("%s %d %d", message.Name, &message.data, &message.priority); v.push(message); //入列; } } return 0;}