(priority_queue)优先队列的应用
定义:priority_queue<Type, Container, Functional>
需要包含头文件
作用:可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队。
和队列基本操作相同:
- top 访问队头元素
- empty 队列是否为空
- size 返回队列内元素个数
- push 插入元素到队尾 (并排序)
- emplace 原地构造一个元素并插入队列
- pop 弹出队头元素
- swap 交换内容
当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。
`//升序队列,小顶堆
priority_queue <int,vector<int>,greater<int> > q;
//降序队列,大顶堆
priority_queue <int,vector<int>,less<int> >q;
//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)
自定义类型的例子
#include <iostream>
#include <queue>
using namespace std;
//方法1
struct tmp1 //运算符重载<
{
int x;
tmp1(int a) {x = a;}
bool operator<(const tmp1& a) const
{
return x < a.x; //大顶堆
}
};
//方法2
struct tmp2 //重写仿函数
{
bool operator() (tmp1 a, tmp1 b)
{
return a.x < b.x; //大顶堆
}
};
int main()
{
tmp1 a(1);
tmp1 b(2);
tmp1 c(3);
priority_queue<tmp1> d;
d.push(b);
d.push(c);
d.push(a);
while (!d.empty())
{
cout << d.top().x << '\n';
d.pop();
}
cout << endl;
priority_queue<tmp1, vector<tmp1>, tmp2> f;
f.push(b);
f.push(c);
f.push(a);
while (!f.empty())
{
cout << f.top().x << '\n';
f.pop();
}
}
题目
题目描述
自然界有一种物质,同种两个物质结合需要消耗的能量为两个物质的质量和。假设只能两两结合,根据输入的该类物质碎片质量,求全部碎片结合成一个整体,需要的最小能量。
Input Format
碎片总个数0<n<=50
n个碎片的质量【取值范围(0,10000)的n个整数】
Output Format
两两结合需要的最小能量
Example
Input
5
1 4 5 2 6
Output
39
#include<iostream>
#include<queue>
using namespace std;
int main()
{
int n, t;
int sum = 0;
priority_queue<int, vector<int>, greater<int>> q;
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> t;
q.push(t);
}
for(int i = 0; i < n - 1; i++)
{
int a, b;
a = q.top();
q.pop();
b = q.top();
q.pop();
sum += a + b;
q.push(a + b);
}
cout << sum << endl;
return 0;
}
参考来自:https://blog.csdn.net/weixin_36888577/article/details/79937886