题目描述
原题
You have N cards. On the i-th card, an integer A_i is written.
For each j = 1, 2, …, M in this order, you will perform the following operation once:
Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j.
Find the maximum possible sum of the integers written on the N cards after the M operations.
翻译
你有N张牌。在第i张卡上,写入一个整数A_i。
对于每个j=1,2。。。,M按此顺序,您将执行以下操作一次:
操作:最多选择B_j张牌(可能为零)。用C_j替换写在每个选定卡片上的整数。
求写在N张卡片上的整数在M次运算后的最大可能和。
输入输出格式
Input
Input is given from Standard Input in the following format:
N M
A_ 1 A_2 … A_N
B_1 C_1
B_2 C_2
.
.
.
B_M C_M
Output
Print the maximum possible sum of the integers written on the N cards after the M operations.
输入输出样例
Sample 1
Input:
3 2
5 1 4
2 3
1 5
Output:
14
Sample 2
Input:
10 3
1 8 5 7 100 4 52 33 13 5
3 10
4 30
1 4
Output:
338
Sample 3
Input:
3 2
100 100 100
3 99
3 99
Output:
300
Sample 4
Input:
11 3
1 1 1 1 1 1 1 1 1 1 1
3 1000000000
4 1000000000
3 1000000000
Output:
10000000001
分析
贪心算法,大的换小的。
是人类的都知道,要尽量先把大的换进去
最笨的方法:
用优先队列(小根堆)记录n个数,然后循环输入b和c,如果比最小的大,把top换掉,若比最小的小则进行下一次输入,因为把这个c换进去就得不到最小的总和了。
这种方法时间复杂度有点大,所以我们需要进行优化。
AC方法
n个数仍然用优先队列存储
由于要尽量把大的换进去,所以我们可以先输入完全部的数据,对b和c进行排序(按c的从大到小排序)
然后大的换小的,当数据已经小于或等于所有数时,就退出,因为这是已经求出了最大值。
最后一步,循环求和并输出
Code
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> > q;
int n,k,i,j,x,top;
struct node
{
int no,s;
}e[110000];
long long ans=0;
bool cmp(node x,node y)
{
return x.s>y.s;
}
int main()
{
scanf("%d%d",&n,&k);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
q.push(x);
}
for(i=1;i<=k;i++)
scanf("%d%d",&e[i].no,&e[i].s);
sort(e+1,e+1+k,cmp);
for(i=1;i<=k;i++)
{
while(e[i].no>0)
{
if(q.top()>=e[i].s)
break;
q.pop();
q.push(e[i].s);
e[i].no--;
}
}
for(i=1;i<=n;i++)
{
ans+=q.top();
q.pop();
}
printf("%lld",ans);
return 0;
}