hdu 1509 1873()病人要看病 优先队列(符号重载)

优先队列,是堆的数据结构。子节点不大于父节点,根节点为最大值,故取出的是最大值。

优先队列,1权值越小优先级高,2权值相等,先输入的优先级高,即索引越小优先级越高。

重载符号:

struct node
{
    char str[100];
    int par;
    int pri;
    int index;
    bool operator<(const node &x) const
    {
        if(pri!=x.pri)
            return pri>x.pri;  //按照pri越小优先级越大
        else
            return index>x.index;//按照索引越小优先级越大
    }
};

代码如下:

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<string>
 4 #include<string.h>
 5 #include<algorithm>
 6 #include<math.h>
 7 #include<vector>
 8 #include<stack>
 9 #include<queue>
10 
11 using namespace std;
12 struct node
13 {
14     char str[100];
15     int par;
16     int pri;
17     int index;
18     bool operator<(const node &x) const
19     {
20         if(pri!=x.pri)
21             return pri>x.pri;  //按照pri越小优先级越大
22         else
23             return index>x.index;//按照索引越小优先级越大
24     }
25 };
26 
27 
28 int main()
29 {
30     priority_queue<node> que;
31     int k=0;
32     char cmd[4];
33     node  temp;
34     while(cin>>cmd)
35     {
36         if(strcmp(cmd,"GET")==0)
37         {
38             if(!que.empty())
39             {
40                 temp=que.top();
41                 cout<<temp.str<<' '<<temp.par<<endl;
42                 que.pop();
43 
44             }
45             else
46             {
47                 cout<<"EMPTY QUEUE!"<<endl;
48             }
49         }
50         else
51         {
52             cin>>temp.str>>temp.par>>temp.pri;
53             temp.index=++k;
54             que.push(temp);
55         }
56     }
57     return 0 ;
58 }

注意:本题的输入输出

用scanf和cin输入,不能接受空格,tab,回车,换行,遇到则停止输入。

gets(),可以无上限读取,遇到换行符停止。

hdu 1873

优先队列为一个数组,而且如果令队列为全局变量,要注意队列清空。如果放在循环体内就不需要清空了。

#include<string>
#include<string.h>
#include<queue>
#include<map>
#include<stack>
#include <iostream>
#include <stdio.h>
#include <cmath>
using namespace std;
int n;
int i,j;
char str[4];
struct man{
    int id;
    int level;
    bool operator<(const man m) const{     //级别越高,优先级越大, 级别相等则 编号越小优先级越大。
        if(level!=m.level)
            return level<m.level;
        else return id>m.id;
    }
};
priority_queue<man>q[3];  //全局变量,故需要清空

int main()
{
    int id,level,doc;
    man people;
while(cin>>n){
//优先队列数组清空
for(i=0;i<3;i++) while(!q[i].empty()) q[i].pop();
//////////////////// id
=1; while(n--){ cin>>str>>doc; if(!strcmp(str,"IN")) { cin>>people.level; people.id=id++; q[doc-1].push(people); } else{ if(!q[doc-1].empty()){ cout<<q[doc-1].top().id<<endl; q[doc-1].pop(); } else cout<<"EMPTY"<<endl; } if(!strcmp(str,"IN")){ } } } return 0; }
原文地址:https://www.cnblogs.com/zn505119020/p/3561976.html