C++优先队列

来源:互联网 发布:商标设计软件 编辑:程序博客网 时间:2024/06/16 05:20

发现优先队列这个东西需要学一下,今天中午闲着没事把优先队列学了一下,stl里很简单,重载一下声明啥的,优先队列原理是大根堆,哇,看了一会看不懂,算了。贴一下优先队列的基本用法,顺便找几道水题刷刷看。

用法:

#include <bits/stdc++.h>using namespace std;struct node{    int x;    bool operator <(const node &a)const{//这个地方的符号必须是<因为stl中的优先队列只认识这个符号。       return a.x<x;//越小的优先级越高;   }};int main(){    priority_queue<node> Q;//优先队列的声明        //实验,从大到小入队,出队从小到大    node s;    for(int i=5;i>0;i--){        s.x=i;        Q.push(s);    }    while(!Q.empty()){        cout<<Q.top().x<<endl;        Q.pop();    }}


hdu1873 看病要排队 http://acm.hdu.edu.cn/showproblem.php?pid=1873

思路:完美用到优先队列,要注意一点就是要开一个队列数组,还有就是判断条件的重写。

代码:

#include <iostream>#include <queue>#include <string>using namespace std;struct node{    int pai;//排队的先后    int you;//优先级    friend bool operator<(node a,node b)//<代表b的优先级要高于a的优先级    {        if(a.you<b.you) return true;        if(a.you==b.you&&a.pai>b.pai) return true;        return false;    }};int main(){    priority_queue<node>Q[4];    node temp;    int m;    while(cin>>m){        for(int i=1;i<4;i++)            while(!Q[i].empty())                Q[i].pop();        int j=1;        for(int i=1;i<=m;i++){            string s;            cin>>s;            if(s[0]=='I'){                int a,b;cin>>a>>b;                temp.pai=j,temp.you=b;j++;                Q[a].push(temp);            }            else{                int a;cin>>a;                if(Q[a].empty()) cout<<"EMPTY"<<endl;                else{                    cout<<Q[a].top().pai<<endl;                    Q[a].pop();                }            }        }    }}



0 0