C++ 优先队列
头文件
#include<queue>
操作符重载
在结构体中定义一个
friend bool operator<(node n1,node n2)
return n1.elem>n2.elem;
这是根据node结构体中的elem升序构建的一个操作符
如果想要降序就把>换成<
定义
priority_queue<node>q;
其中node为结构体名称,q为优先队列名称
示例
http://acm.hdu.edu.cn/showproblem.php?pid=1509
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct node
{
char str[100];
int par;
int pri;
int index;
friend bool operator<(node n1,node n2)
{
if(n1.pri==n2.pri)
return n1.index>n2.index;
else
return n1.pri>n2.pri;
}
};
int main()
{
priority_queue<node>q;
int k=0;
char cmd[4];
node temp;
while(cin>>cmd)
{
if(strcmp(cmd,"GET")==0)
{
if(!q.empty())
{
temp=q.top();
q.pop();
cout<<temp.str<<' '<<temp.par<<endl;
}
else
cout<<"EMPTY QUEUE!"<<endl else="" cin="">>temp.str>>temp.par>>temp.pri;
temp.index=++k;
q.push(temp);
}
}
return 0;
}
</endl></node></cstring></queue></iostream>