D. Wooden Toy Festival codeforces1840D

Problem - D - Codeforces

题目大意:有一个长度为n的数组a,可以任意选择的3个数,使所有a[i]距离其中最近的数的最大距离最小,求这个最小值

1<=n<=2e5;1<=a[i]<=1e9

思路:我们要让最大距离最小,所以这三个数分别都要往中间放更优,那么我们设当前的最大距离最小值为x,三个数为y1,y2,y3,他们能掌管的范围就是[y[i]-x,y[i]+x]那么显然x越大三个数总共掌管的范围就越大,我们的目标是要总的范围囊括从小到大所有数,所以有单调性的约束问题显然可以二分枚举x,首先将a排序并去重,然后对于每个枚举的x,用upper_bound查找当前范围外的最小值+2*x可以找到每个数的掌管范围右边界,然后下一个数的位置即是下一个位置的左边界,如果某一时刻右边界囊括到了n,就说明x是可以的,然后缩小x试试,如果x不行,就增大试试,直到得到答案

//#include<__msvc_all_public_headers.hpp>
#include<bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
typedef long long ll;
ll mylog(ll x)
{
	ll ret = 0;
	ll now = 1;
	while (now<=x)
	{
		now <<= 1;
		ret++;
	}
	return ret;
}
ll a[N];
ll n;
bool check(ll x)
{
	int it1 = upper_bound(a + 1, a + n + 1, a[1] + 2 * x)-a;//掌管范围的右边界
	if (it1 > n)
	{//任意时刻右边界囊括n要立即返回
		return 1;
	}
	int it2 = upper_bound(a + it1, a + n + 1, a[it1] + 2 * x) - a;
	if (it2 > n)
		return 1;
	int it3 = upper_bound(a + it2, a + n + 1, a[it2] + 2 * x) - a;
	if (it3 > n)
		return 1;
	return 0;
}
int main()
{
	cin.tie(0);
	cout.tie(0);
	ios::sync_with_stdio(false);
	int t;
	cin >> t;
	while (t--)
	{
		
		cin >> n ;
		for (int i = 1; i <= n; i++)
		{
			cin >> a[i];
		}
		sort(a + 1, a + n + 1);//排序
		ll it=unique(a + 1, a + n + 1)-a;//去重能稍微优化一点时间,不去重也行,但是其实用不到重复的数
		n = it - 1;
		ll l = 0, r = a[n];
		ll ans;
		while (l <= r)
		{
			ll mid = (l + r) / 2;
			if (check(mid))
			{
				r = mid -1;
				ans = mid;
			}
			else
			{
				l = mid + 1;
			}
		}
		cout << ans << endl;
	}
	return 0;
}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

timidcatt

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值