前言
P.S.暑假集训的时候的一道模拟赛中的题,用集训给的有且仅有的一次超强数据干爆了一些题解,现在也来补篇题解。
思路分析
看到这个题面的瞬间相信大家都会想到贪心。但是写完贪心后一测,不难发现直接贪心得到的不一定是最优解,所以这个贪心是需要反悔的。
首先考虑正常的贪心,用两个堆压入用了券的值和不用券的值,每次选择最小价格的牛买入。最后就可以得到这种情况下最多能买多少牛。
接着考虑反悔,对于我们反悔的代价便是用券的值减去不用券的值,也就是多花费的钱数。多开一个堆,在每次买牛的把这个反悔代价放入堆中。
对于每头牛都先考虑买下来,如果没钱了考虑反悔一个然后用优惠券买下来。如果都不行了那就肯定买不了更多的牛了。
代码
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,k,m,ans;
struct node{int p,c;}a[50010];
priority_queue<int> q;
int read()
{
char c=getchar();int x=0,f=1;
while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}
while(isdigit(c)) x=(x<<1)+(x<<3)+(c^48),c=getchar();
return x;
}
bool cmp1(node tmp1,node tmp2){return tmp1.c<tmp2.c;}
bool cmp2(node tmp1,node tmp2){return tmp1.p<tmp2.p;}
signed main()
{
n=read(),k=read(),m=read();
for(int i=1;i<=n;i++) a[i].p=read(),a[i].c=read();
sort(a+1,a+1+n,cmp1);
if(k<n) sort(a+k+1,a+1+n,cmp2);
for(int i=1;i<=n;i++)
{
if(k)
{
if(m<a[i].c) break;
k--,ans++,m-=a[i].c;
q.push(-a[i].p+a[i].c);
}
else if(m>=a[i].p)
{
ans++,m-=a[i].p;
if(!q.empty()&&a[i].p-a[i].c+q.top()>0) m+=a[i].p-a[i].c+q.top(),q.pop(),q.push(-a[i].p+a[i].c);
}
else if(!q.empty()&&m+a[i].p-a[i].c+q.top()>=a[i].p)
{
ans++,m+=-a[i].c+q.top();
q.pop(),q.push(-a[i].p+a[i].c);
}
}
printf("%lld\n",ans);
return 0;
}