https://www.cnblogs.com/kylara/p/9804251.html
大根堆:
1.priority_queue<int> q;【默认
2. priority_queue< node,vector<node>,less<node> > q;【自带比较函数
小根堆:
priority_queue< node,vector<node>,greater<node> > q;【自带比较函数
重载运算符:
1.定义struct node 之后重载
这是小根堆
priority_queue<node>q;//或 priority_queue< node,vector<node>,less<node> >q;
bool operator<(node a,node b)//或写做(const node &a,const, node &b) 更快
{
return a.y>b.y;//以y从小到大排序
}
2.在定义struct node时重载
struct node
{
int id,v;
bool operator<(const node &a) const{
return v<a.v;//以v从大到小排序
}
};
priority_queue<node>q;
3.定义友元操作类重载函数
struct node
{
int v;
friend bool operator<(const node &a,const node &b){
return a.v<b.v; //按v从大到小排列
}
};
priority_queue<node>q;
自定义比较函数模板结构
struct cmp
{
bool operator ()(const node &a, const node &b)
{
return a.v>b.v;// 按照v从小到大排列
}
};
priority_queue<node,vector<node>,cmp> q;
#include <iostream> #include <cstdio> #include <queue> #include <vector> using namespace std; struct node { int id,v; //id为位置,v为权值 bool operator<(const node &a) const { return v<a.v;//以v从大到小排序 } }; priority_queue<node> q; int main() { for (int i=1;i<=5;i++) { int a,b; cin>>a>>b; node temp; temp.id=a; temp.v=b; q.push(temp); } cout<<"the result is "<<endl; while (q.size()>0) { node aa; aa=q.top(); q.pop(); cout<<aa.id<<" "<<aa.v<<endl; } } /* 1 7 9 5 3 8 4 6 6 4 the result is 3 8 1 7 4 6 9 5 6 4 */
#include <iostream> #include <cstdio> #include <queue> #include <vector> using namespace std; struct node { int id,v; //id为位置,v为权值 bool operator<(const node &a) const { //保证位置编号从小到大,位置编号一样则权值从小到大
//有双关键字时一定要看下第一个关键是否相等 if (id==a.id) return v>a.v; else return id>a.id; //return v<a.v;//以v从大到小排序 } }; priority_queue<node> q; int main() { for (int i=1;i<=5;i++) { int a,b; cin>>a>>b; node temp; temp.id=a; temp.v=b; q.push(temp); } cout<<"the result is "<<endl; while (q.size()>0) { node aa; aa=q.top(); q.pop(); cout<<aa.id<<" "<<aa.v<<endl; } } /* 1 3 1 9 1 2 9 8 7 6 the result is 1 2 1 3 1 9 7 6 9 8 */