天天看點

C++優先隊列

發現優先隊列這個東西需要學一下,今天中午閑着沒事把優先隊列學了一下,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();
                }
            }
        }
    }
}