优先队列
基本数据类型的优先级设置:
即可以直接使用的数据类型
优先队列对他们的优先级设置一般是数字越大的优先级越高,因此队首是优先级最大的那个(如果是 char 类型,则是字典序最大的)。以 int 型为例下面两种是等价的:
priority_queue<int>q;
priority_queue<int,vector<int>,less<int> >q;
可以发现第二种定义方式的尖括号内多出了两个参数:其中 vector
第三个参数 less
结构体的优先级设置:
第一种
使用友元函数
struct Node
{
string name;
int price;
//friend bool operator<(const Node &son,const Node &father)
//建议使用上面的引用来提高效率
friend bool operator<(Node son,Node father)
{
//大根堆
return son.price<father.price;
//小根堆
//return son.price>father.price;
}
};
priority_queue<Node> q;
第二种
struct Node
{
string name; //名字
int price; //价格
};
struct cmp{
bool operator() (Node son,Node father){
//儿子结点小于等于父亲结点是大根堆
return son.score < father.score;
/*
结点小于等于父亲结点是小根堆
return son.score > father.score;
*/
}
};
priority_queue<Node,vector<Node>,cmp>;
首先对某一对象建立结构体,现在希望价格高的优先级高,就需要重载(overload)小于号“<”.重载是指对已有的运算符进行重新定义。
可以看到,Node 结构体中增加了一个函数,其中“friend”为友元,后面的"bool operator<(Node son,Node father) " 这里是对小于号进行了重载事实上也仅仅只能对小于号进行重载,重载大于号会编译错误,因为从数学上来讲只需要重载小于号即 son>father<==>father<son,而我们发现 return son.price<father.price ,重载后小于号还是小于号的作用,因此就可一直接定义 Node 类型的优先队列,其内部就是以价格高的水果为优先级高,因此可以直接定义为:
priority_queue<Node> q;
priority_queue的常见用途
priority_queue 可以解决一些贪心问题,也可以对 \(Dijkstra\) 算法进行优化。
需要要注意使用 top() 函数之前,必须用 empty() 判断优先队列是否为空。

浙公网安备 33010602011771号