CF1840D的题解

(一)

比赛结束前 \(5\) 分钟才调出来。

二分答案。先排序,然后从左往右搜,看是否能在 \(3\) 次以内处理完。

由于是绝对值,控制左右数之差 \(\le\) 选定的数 \(x\)

每次固定左节点 \(l\),搜右节点 \(r\),越远越好。

搜完后 \(l=r+1\),继续搜。

特判 \(n\le3\) 的情况。

(二)

AC 代码。

#include<bits/stdc++.h>
#define int long long
using namespace std;
int t,n,a[200001],sum;
int up(int x){
	if(x&1)return x/2+1;
	else return x/2;
}
bool check(int x){
	int l=1,r=1;
	int cnt=0;
	while(++cnt){
		if(cnt==4)return 0;
		while(r<n&&a[r+1]<=a[l]+2*x)r++;
		if(r==n)break;
		l=r+1,r++;
	}
	return 1;
}
signed main(){
	scanf("%lld",&t);
	while(t--){
		scanf("%lld",&n);
		for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
		if(n<=3){
			puts("0");
			continue;
		}
		sort(a+1,a+n+1);
		int l=0,r=up(a[n]-a[1]),ans;
		while(l<=r){
			int mid=(l+r)>>1;
			if(check(mid))ans=mid,r=mid-1;
			else l=mid+1;
		}
		printf("%lld\n",ans);
	}
	return 0;
}
posted @ 2024-03-28 08:19  Jerry_heng  阅读(9)  评论(0)    收藏  举报