题解:P15819 [JOI 2015 Final] 舞会 / Ball

· · 题解

典中典,何时切?

首先根据 P2824 的 trick,我们可以二分并将比 mid 小的标记为 0,把比 mid 大的数标记为 1。这样操作就变成将众数扔最后面。

然后我们考虑 check,或许是我太菜了不会贪心,选择了递推的形式。因为贵族们的形式极像队列,所以我们也用队列来辅助递推。

设辅助队列的元素 f_i 表示将 f_i 变成 1 至少需要多少个 1。转移也比较好想,f_u=\min{f_x+f_y,f_y+f_z,f_x+f_z}。u 是扔过去的点。x,y,z 是原有的点。

考虑初始化,强制为 0 的 f 设成正无穷,强制为 1 的 f 设成 0,无限制设成 1 就行了,比较好写。

时间复杂度 \Theta(n \times \log V),V 为值域,如果你离散化是 \Theta(n \times \log n) 的。

#include<bits/stdc++.h>
#define int long long
#define endl "\n"
#define upto(i,x,y) for(int i=x;i<=y;i++)
using namespace std;
int n,m;
int f[100005];
int g[100005];
deque<int> q;
bool check(int mid){
    while(!q.empty())q.pop_back();
    int cnt1=0;
    upto(i,1,n-m)if(g[i]>=mid)cnt1++;
    for(int i=1;i<=n;i++){
        if(f[i]){
            if(f[i]<mid)q.push_back(INT_MAX);
            else q.push_back(0);
        }else q.push_back(1);
    }
    while(q.size()>1){
        int x=q.front();q.pop_front();int y=q.front();q.pop_front();int z=q.front();q.pop_front();
        q.push_back(x+y+z-max({x,y,z}));//就是转移的式子化简了一下。
    }
    return q.front()<=cnt1;
}
signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n>>m;
    upto(i,1,m){
        int u,p;
        cin>>u>>p;
        f[p]=u;
    }
    upto(i,1,n-m)cin>>g[i];
    int l=1,r=1e9,ans=1;
    while(l<=r){
        int mid=l+r>>1;
        if(check(mid))ans=mid,l=mid+1;
        else r=mid-1;
    }
    cout<<ans;
    return 0;
}