priority queue在许多的特别场合还是很实用的,优先队列是依据堆(二叉树)实现的,效率是O(lgn),因为它带来的便利,人们可以少写很多的代码,所以学习它是有必要的。
很多时候我们会自己定义比较函数,因为标准库默认使用元素类型的<操作符来确定它们之间的优先级关系,所以如果用>在g++编译器中编译不过,在函数中operator旁边还是用<吧,或者使用()。使用”priority_queue<int,vector<int>,greater<int> >“类似的语句可以将大到小的默认顺序改成小到大(头文件是<functional>,我们也可以自己写一个比较类设定优先级。
struct cmp{
bool operator()(type a,type b){
return -------;
}
};
相关的结果:
v.size:5
7
5
3
2
1
v.size:0
v2 从小到大输出:
1
2
3
5
7
自定义比较的V3输出:
1
2
3
5
7
点输出优先级:与原点的曼哈顿距离。
(12,0)
(6,5)
(3,7)
(0,9)
(3,4)
一个应用例子:
nefu 355 合成陨石
http://acm.nefu.edu.cn/JudgeOnline/problemshow.php?problem_id=355
大意:一堆石子两两合并,合并的新石子加入原石堆中,每次合并产生的新石子质量是合并石子的质量和,且记录下来,请问最后的最小的质量和