题解:P8170 [eJOI 2021] Waterfront

· · 题解

若至卡常题。

直接贪心,每次减去最后高度最大的灌木,复杂度 O(nm\log V),先基数排序,在用堆维护前 k 大可以做到 O(nm+nk\log V),但是会被卡。

另一个做法是 O(nm\log V) 的二分答案,二分后算出每个灌木被减的次数然后贪心模拟,同样会被卡。

我们充分发扬人类智慧,把直接贪心的做法改为维护两个堆分别表示高度 <x 和高度 \geq x 的灌木,对第二个堆堆顶操作。每次增长后,将第一个堆高度 \geq x 的前缀弹出并加入第二个堆。这样显然是错的,但是能得到一个和答案差的不多的解 R。

然后先检验答案是否在 [R-10,R] 内,如果答案不在内就二分答案,并将二分边界设为 [0,R] 即可。

这样跑得飞快,极限数据只需要 700 毫秒左右。

最坏复杂度 O(nm\log V)。

#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/priority_queue.hpp>
using namespace std;
using namespace __gnu_pbds;
int n,m,k,x;
struct node{
    int h,d,cnt,edh;
    bool operator < (const node &b) const{
        return edh<b.edh;
    } 
}a[10005],b[10005];
inline int edh(node b){
    return b.h+b.d*m-x*b.cnt;
}
inline int nowh(node b,int t){
    return b.h+b.d*t-x*b.cnt;
}
__gnu_pbds::priority_queue<node> Q1,Q2;
bool ck(int mxh){
    for(int i=1;i<=n;i++) a[i]=b[i];
    int allcnt=0;
    for(int i=1;i<=n;i++){
        if(a[i].h+a[i].d*m<=mxh) continue;
        a[i].cnt=(a[i].h+a[i].d*m-mxh+x-1)/x;
        allcnt+=a[i].cnt;
    }
    if(allcnt>m*k) return 0;
    for(int i=1;i<=m;i++){
        int ncnt=0;
        for(int j=1;j<=n;j++){
            a[j].h+=a[j].d;
            if(ncnt<k&&a[j].cnt&&a[j].h>=x){
                int optcnt=min(min(k-ncnt,a[j].cnt),a[j].h/x);
                a[j].h-=x*optcnt,a[j].cnt-=optcnt;
                ncnt+=optcnt;
                allcnt-=optcnt; 
            }
        }
        if(allcnt>(m-i)*k) return 0;
    }
    for(int i=1;i<=n;i++) if(a[i].cnt) return 0;
    return 1;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m>>k>>x;
    for(int i=1;i<=n;i++){
        cin>>a[i].h>>a[i].d;
        a[i].edh=edh(a[i]);
        if(a[i].h>=x) Q2.push(a[i]);
        else Q1.push(a[i]); 
    }
    for(int i=1;i<=m;i++){
        while(!Q1.empty()&&nowh(Q1.top(),i)>=x){
            Q2.push(Q1.top());
            Q1.pop();
        }
        for(int j=1;j<=k;j++){
            if(Q2.empty()) break;
            auto t=Q2.top();
            Q2.pop();
            t.cnt++;
            t.edh=edh(t); 
            if(nowh(t,i)>=x) Q2.push(t);
            else Q1.push(t);
        }
    }
    while(!Q1.empty()){
        Q2.push(Q1.top());
        Q1.pop();
    }
    int mxans=edh(Q2.top());
    for(int i=1;i<=n;i++) b[i]=a[i];
    int l=0,r=mxans,ans=-1;
    for(int i=r-1;i>=max(0,r-10);i--){
        if(!ck(i)){
            cout<<i+1<<"\n";
            return 0;
        }
    }
    while(l<=r){
        int mid=(l+r)/2;
        if(ck(mid)){
            ans=mid;
            r=mid-1;
        }else{
            l=mid+1;
        }
    }
    cout<<ans<<"\n";
    return 0;
}