[CF436E] Cardboard Box 题解

· · 题解

@Nineyx 好闪,拜谢 @Nineyx!

如果每个关卡只有一颗星,那么整道题是简单的,只需要对 a_i 进行排序后贪心取。

现在每个关卡有一颗星、两颗星两种情况。若保持原来的做法,将一个关卡拆分成 a_i,b_i-a_i 两部分,会发现两颗星存在前后顺序关系,不能直接贪心。若直接贪心,可能会存在误选的情况。

为了回避这样的情况,可以反悔。考虑将某颗已经选择的星撤回,但是此时会出现贪心阶段的回撤,于是考虑额外添加两颗星,由贪心过程,这两颗星必须在一关中。于是整道题就变成了对四种决策贪心。

用优先队列分别维护 a_i,b_i-a_i,b_i,-a_i,a_i-b_i 即可。时间复杂度 \mathcal{O}(n\log n)。

:::success[code]

#include<bits/stdc++.h>
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PIR;
const ll maxn=300007,ee=1e18;
ll n,w,a[maxn],b[maxn],stt[maxn],ans;
struct Node{
    priority_queue<PIR,vector<PIR>,greater<PIR> > q;
    ll tar;
    PIR top(void){
        for(PIR x;!q.empty();){
            x=q.top();
            if(stt[x.second]!=tar) q.pop();
            else return q.top();
        }
        return mp(ee,0ll);
    }
    void pop(void){q.pop();}
    void push(ll x,ll id){q.push(mp(x,id));}
}Q[5];
int main(void){
    //freopen("data.in","r",stdin);
    //freopen("data.out","w",stdout);
    ios::sync_with_stdio(0),cin.tie(0);
    cin>>n>>w;
    Q[0].tar=Q[1].tar=0,Q[2].tar=Q[3].tar=1,Q[4].tar=2;
    for(ll i=1;i<=n;i++){
        cin>>a[i]>>b[i];
        Q[0].push(a[i],i),Q[1].push(b[i],i);
    }
    PIR v1,v2,v3,v4,mx;
    for(ll i=1,t,id;i<=w;i++){
        v1=Q[0].top(),v2=Q[2].top();
        v3=Q[3].top(),v3.first+=Q[1].top().first;
        v4=Q[4].top(),v4.first+=Q[1].top().first;
        t=Q[1].top().second;
        ans+=(mx=min({v1,v2,v3,v4})).first;
        if(mx==v1){
            stt[id=v1.second]=1;
            Q[2].push(b[id]-a[id],id);
            Q[3].push(-a[id],id);
        }else if(mx==v2){
            stt[id=v2.second]=2;
            Q[4].push(a[id]-b[id],id);
        }else if(mx==v3){
            stt[id=v3.second]=0,stt[t]=2;
            Q[0].push(a[id],id),Q[1].push(b[id],id);
            Q[4].push(a[t]-b[t],t);
        }else{
            stt[id=v4.second]=1,stt[t]=2;
            Q[2].push(b[id]-a[id],id),Q[3].push(-a[id],id);
            Q[4].push(a[t]-b[t],t);
        }
    }
    cout<<ans<<"\n";
    for(ll i=1;i<=n;i++) cout<<stt[i];
    cout<<"\n";
    return 0;
}

:::

本文的重点是这个做法的正确性。这里给出一个证明方法。

考虑归纳证明。选择 0,1 颗时,做法显然最优。设已经得出选择 w 颗时做法最优,尝试拓展到 w+1。

下面证明:w\to w+1 时,减掉 1 颗是不劣的。

如果减掉 c\ge2 颗,内容为 S,并新增了 c+1 颗,可以分成两种情况:

这样就证明了减掉 \le1 颗星是不劣的。显然上文策略已经覆盖所有减掉 \le1 颗星的情况。

于是就证明了贪心策略正确。