题解:CF2013D Minimize the Difference

· · 题解

思路

发现最大值和最小值是有单调性的,直接二分最大值和最小值即可。

代码

#include<bits/stdc++.h>
#define yes cout<<"YES\n"
#define no cout<<"NO\n"
#define pb push_back

using namespace std;
typedef long long LL;
typedef pair<LL,LL> PII;

const LL N=2e5+5;
LL n,res;
vector<LL>a(N);

bool check1(LL val) {
    LL res=0;
    for(int i=1;i<=n;i++){
        if(val-a[i]>res&&a[i]<val){
            return 0;
        }
        if(a[i]>val){
            res+=a[i]-val;
        }
        if(a[i]<val){
            res-=val-a[i];
        }
    }
    return 1;
}
bool check2(LL val){
    LL res=0;
    for(int i=1;i<=n;i++) {
        if(a[i]>val){
            res+=a[i]-val;
        }
        if(a[i]<val){
            res=max(0ll,res-=val-a[i]);
        }
    }
    if(res) return 0;
    return 1;
}

void solve(){
    cin>>n;
    for(LL i=1;i<=n;i++){
        cin>>a[i];
    }
    LL l=1,r=1e12+1,mid,ma,mi;
    while(l<=r){
        mid=(l+r)>>1;
        if(check1(mid)){
            l=mid+1;
            ma=mid;
        }else{
            r=mid-1;
        }
    }
    l=1,r=1e12+1;
    while(l<=r){
        mid=(l+r)>>1;
        if(check2(mid)){
            r=mid-1;
            mi=mid;
        }else{
            l=mid+1;
        }
    }
    cout<<mi-ma<<"\n";
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);cout.tie(0);
    LL t=1;cin>>t;
    while(t--) solve();
    return 0;
}
/*

*/