HDU 1509 Windows Message Queue(优先队列+重载运算符)

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或者put,get是输出信息队列中的第一条信息,为空就输出“EMPTY QUEUE!”

put是输入一条信息,名字,参数和优先级

按优先级来输出信息,优先级相同则按FIFO,也就是first input first output,先进先出(需要重载运算符)

#include <iostream>
#include <map>
#include <utility>
#include <queue>
using namespace std;

struct info
{
    int pri;
    int num;
    int t;
    string s;
    friend bool operator < (const info &a,const info &b)//重载运算符,也可以写在结构体外面,有多种写法
    {
        return a.pri==b.pri ? (a.t>b.t) : (a.pri>b.pri);
    }

}a;//定义了一个结构体
priority_queue<info> pq;
map <int ,int >M;//也可以不用map
int main()
{
    string s,s1;
    int num,pri;
    int cnt=0;
    while(cin>>s)
    {
        cnt++;
        if(s=="PUT")
        {
            cin>>a.s>>a.num>>a.pri;
            a.t=M[a.pri]++;//用于处理优先级相同的情况,map就这个作用,当让也可以不用map,用我的cnt
//           a.t=cnt;同样是对的
            pq.push(a);
        }
        else
        {
            if(pq.empty())
                cout<<"EMPTY QUEUE!"<<endl;
            else
            {
                a=pq.top();
                pq.pop();
                cout<<a.s<<" "<<a.num<<endl;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40733911/article/details/81432479