跳到正文

题解

题解:CF2013D Minimize the Difference

Defy_HeavenS约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年10月7日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 2 分钟
题目
CF2013D

版本

  1. v1当前

思路

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

代码

C++
#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;
}
/*

*/
原文
存档评论1 条抓取于