优先队列用法
#include <queue>
std::priority_queue<TypeName> q; // 数据类型为 TypeName,默认使用底层容器 vector std::priority_queue<TypeName, Container> q; // 使用 Container 作为底层容器 std::priority_queue<TypeName, Container, Compare> q; // 使用 Container 作为底层容器,使用 Compare 作为比较类型
priority_queue<int> q1; //为大根堆
priority_queue<int, vector<int> > q2; //为大根堆
priority_queue<int, deque<int>, greater<int> > q3; // q3 为小根堆
//维护一个堆:只保证根是最大or最小的。
for (int i = 1; i <= 5; i++) q1.push(i);
cout << q1.top() << endl;
q1.pop();
cout << q1.size() << endl;
// 输出结果 :4
for (int i = 1; i <= 5; i++) q3.push(i);
cout << q3.top() << endl;
// 输出结果 : 1
多元排序:struct
struct str
{
int val,id;
bool operator < (const str &x) const
{
return val < x.val;
}
};priority_queue<str> q;
----------------------------------------------------
str dd = {a[x],x};
q.push(dd);
str now = q.top();
q.pop();
例题
题意简述
“Jeopardy!”的决赛将有n问题,每个问题都有对应的得分ai,其中有m个问题可以选择不得分,而将现有总得分翻倍。你可以安排关卡的通过顺序和策略,求最大得分。
输入格式:
第一行包含两个整数。n和m(1<=n,m<=100;m<=min(n,30))分别代表问题总数和可翻倍问题总数。第二行包含n个整数a1,a2,...,an(1<=ai<=1e7)代表每个问题的价值;第三行包含m个整数b1,b2,...,bm(1<=bi<=n)代表可翻倍问题的编号。问题编号是从1到n。
输出格式:
一行一个数字,表示通过所有关卡最大得分。保证该答案在64位带符号整型范围内。
输入 #1
4 1 1 3 7 5 3 输出 #1 18输入 #2
3 2 10 3 8 2 3 输出 #2 40输入 #3
2 2 100 200 1 2 输出 #3 400
题解代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int mo = 1e3;
const int N = 1e5 + 5;
bool b[200];
int a[200];
ll ans = 0;
struct str
{
int val,id;
bool operator < (const str &x) const
{
return val < x.val;
}
};
priority_queue<str> q;
void solve()
{
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
int x;
for (int i = 1; i <= m; i++)
{
cin >> x;
b[x] = 1;
str dd = {a[x],x};
q.push(dd);
}
for (int i = 1; i <= n; i++)
if (b[i] == 0)
{
ans += a[i];
}
while (!q.empty())
{
str now = q.top();
// cout << now.id << endl;
ans = max(ans * 2, ans + a[now.id]);
// cout << "ans= " << ans << endl;
q.pop();
}
cout << ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
solve();
return 0;
}