【贪心+堆】AtCoder Grand Contest(018)C[Coins]题解

本文介绍了一种解决资源分配问题的算法,旨在从X+Y+Z个人中选出X人提供金币、Y人提供银币、Z人提供铜币,使得提供的总币数最大化。通过按差值排序和使用堆来实现高效求解。

题目概述

X+Y+Z 个人,每个人有 Ai 个金币, Bi 个银币, Ci 个铜币。现在选 X 个人提供金币, Y 个人提供银币, Z 个人提供铜币。求最多提供多少币(金银铜)。

解题报告

挺好的题目,可以完美地干翻像我这样的蒟蒻。我们先考虑只有金币和银币的最优策略:按照 BiAi 从小到大排序,然后前 X 个取 A ,后 Y 个取 B

如果有铜币怎么办?我们可以在原来的基础上处理。由于有了铜币,原先的方法不一定最优,但要取 A 一定还是靠前取,取 B 也一定还是靠后取。所以我们枚举分界点 i ,金币全在 [1,i] 取,银币则在 [i+1,n] 取,而铜币先假装都取了。那么选择金币和银币时应该优先选择 ACBC 中大的,用堆实现即可。

示例程序

#include<cstdio>
#include<algorithm>
#define fr first
#define sc second
#define mp make_pair
using namespace std;
typedef long long LL;
const int maxn=100000;

int X,Y,Z,n;LL ans,now,C;
struct data {int a,b,c;bool operator < (const data &c) const {return b-a<c.b-c.a;}};
data a[maxn+5];bool vis[maxn+5];
int ss,sb,Hs[maxn+5];pair<int,int> Hb[maxn+5];

#define Eoln(x) ((x)==10||(x)==13||(x)==EOF)
inline char readc()
{
    static char buf[100000],*l=buf,*r=buf;
    if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
    if (l==r) return EOF;return *l++;
}
inline int readi(int &x)
{
    int tot=0,f=1;char ch=readc(),lst='+';
    while ('9'<ch||ch<'0') {if (ch==EOF) return EOF;lst=ch;ch=readc();}
    if (lst=='-') f=-f;
    while ('0'<=ch&&ch<='9') tot=(tot<<1)+(tot<<3)+ch-48,ch=readc();
    return x=tot*f,Eoln(ch);
}
#define Push_s(x) Hs[++ss]=(x),push_heap(Hs+1,Hs+1+ss)
#define Pop_s() pop_heap(Hs+1,Hs+1+ss--)
#define Push_b(x,ID) Hb[++sb]=mp((x),(ID)),push_heap(Hb+1,Hb+1+sb)
#define Pop_b() pop_heap(Hb+1,Hb+1+sb--)
int main()
{
    freopen("C.in","r",stdin);
    freopen("C.out","w",stdout);
    readi(X);readi(Y);readi(Z);n=X+Y+Z;
    for (int i=1;i<=n;i++) readi(a[i].a),readi(a[i].b),readi(a[i].c),C+=a[i].c;
    sort(a+1,a+1+n);for (int i=X+1;i<=n;i++) Push_b(a[i].b-a[i].c,i);
    for (int i=1;i<=Y;i++) now+=Hb[1].fr,vis[Hb[1].sc]=true,Pop_b();
    for (int i=1;i<=X;i++) now+=a[i].a-a[i].c,Push_s(a[i].c-a[i].a);ans=now;
    for (int i=X+1;i<=n-Y;i++)
    {
        if (a[i].c-a[i].a<Hs[1]) now+=(LL)Hs[1]+a[i].a-a[i].c,Pop_s(),Push_s(a[i].c-a[i].a);
        if (vis[i])
        {
            while (vis[Hb[1].sc]) Pop_b();vis[Hb[1].sc]=true;
            now+=(LL)Hb[1].fr-a[i].b+a[i].c;Pop_b();
        }
        vis[i]=true;ans=max(ans,now);
    }
    return printf("%lld\n",ans+C),0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值