queue队列
- 先进先出
![image]()
priority_queue优先队列
- 底层逻辑是堆
- 按照一定的优先级进行排序的
- 从大到小
![image]()
修改比较函数的方法
- 自定义比较函数
struct Compare
{
bool operator()(int a,int b)//operator()重载运算符
{
return a > b;
}
};
int main()
{
priority_queue<int,vector<int>,Compare> pq;
- 自定义比较函数
auto compare = [](int a,int b){
return a > b;
};
priority_queue<int,vector<int>,decltype(compare)> pq(compare);
- 如果队列中的元素类型比较简单,可以直接使用greater来修饰比较方法
priority_queue<int,vector<int>,greater<int>>pq;
greater函数对象定义在<functional>头文件中
deque双端队列
- 允许两端进行插入和删除
- 常用函数
![image]()
示例1
![image]()
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);//取消同步流
int m;cin >> m;//
queue<string> V,N;//字符队列V N
while(m --)//while遍历循环m次
{
string op;cin >> op;//定义op,输入op
if(op == "IN")
{
string name,q;cin >> name >> q;
if(q == "V")V.push(name);//加入队列
else N.push(name);
}else
{
string q;cin >> q;
if(q == "V")V.pop();
else N.pop();
}
}
while(V.size())//遍历
{
cout << V.front() << '\n';//输出打印V栈顶元素
}
while(N.size())
{
cout << N.front() << '\n';
N.pop();
}
return 0;
}
示例2
![image]()
#include<bits/stdc++.h>
using namespace std;
using ll = long long;//根据题目给的范围开
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);//取消同步流
int n;cin >> n;//输入总共的数字的数目
priority_queue<ll,vector<ll>,greater<ll>> pq;//声明优先队列,类型ll,从小到大排,数据结构简单使用greater
for(int i = 1;i <= n; ++ i)//遍历输入次数
{
ll x;cin >> x;//输入的数字
pq.push(x);//将数字插入
}
ll ans = 0;
while(pq.size() >= 2)//pq的长度大于2执行while循环
{
ll x = pq.top();pq.pop();//赋值弹出
ll y = pq.top();pq.pop();
ans += x + y;
pq.push(x + y);
}
cout << ans <<'\n';
return 0;
}