题意:
有 n n n 个人需要投票,你想让所有人都投票给你,有两种方式,一种是给第 i i i 人 p i pi pi 的钱,另一种是当已经有 m i mi mi 的人投票给你,则 i i i 会免费投票给你,求最后所有人都投票给你的最小花费。
题解:
首先对于容易跟风的人,我们尽可能的不去贿赂他,而不容易跟风的人,我们要优先贿赂他们。
因此先按 m i mi mi 排序,然后从大到小对 m i mi mi 遍历,对于所有 m i mi mi 值为 x x x 的人,我们将其放入小根堆的优先队列 q q q,假设队列里的人都是想要跟风的,那么我们还得知道哪些人不能跟风,必须要贿赂。
设当前想跟风的人数为 c n t = q . s i z e ( ) cnt=q.size() cnt=q.size()。那么还剩下 n − c n t n-cnt n−cnt 个人,如果 n − c n t < x n-cnt<x n−cnt<x ,那么说明即便剩下的人都已经投票给你,他也无法满足跟风,则这个人必须要被贿赂,那么出队即可。
代码:
#pragma GCC diagnostic error "-std=c++11"
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<unordered_map>
#include<map>
#include<stack>
#include<set>
#include<ctime>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int> pii;
const int mod=1e9+7;
const int MAXN=2e5+5;
const int inf=0x3f3f3f3f;
vector<int> g[MAXN];
priority_queue<int, vector<int>, greater<int>> q;
int main()
{
int t;
scanf("%d", &t);
while(t--){
int n;
scanf("%d", &n);
for (int i = 1; i <= n;i++){
int m,p;
scanf("%d%d", &m, &p);
g[m].push_back(p);
}
ll ans = 0;
for (int i = n - 1; i >= 0;i--){
for(auto j:g[i]){
q.push(j);
}
while(n-q.size()<i){
ans += q.top();
q.pop();
}
}
printf("%lld\n", ans);
while(!q.empty())
q.pop();
for (int i = 0; i <n;i++){
g[i].clear();
}
}
}