跳到正文

题解

P6281 [USACO20OPEN] Social Distancing S

Microperson约 3 分钟
原文
文章信息与版本

文章信息

发布
2021年4月11日
收录
2025年12月12日
更新
2026年11月9日
篇幅
约 3 分钟
题目
P6281

版本

  1. v1当前

题目链接

思路:

当我们看到:

其中D为最近的两头奶牛之间的距离。请帮助奶牛们求出D的最大可能值。

也就是说有N头奶牛放到有草的区间中,使得两头牛之间最小的距离最大。 这就很显而易见了,那就是二分答案了。

这N头牛是要全部放进去的,所以我们需要一层循环处理处每头牛要在的位置,判断当前的 midmid 是否符合就行了。 对于二分答案,我们先来回顾一下二分的模板:

代码
while(l<=r)
	{
		mid=(l+r)/2;
		if(pan(mid)){
			ans=mid;
			l=mid+1;
		}
		else
		r=mid-1;
	}
	cout<<ans<<endl;
   }

这里的边界不是一定的每个题目对应关系可能不同。

接下来就是二分答案了,也就是神奇的 panpan。每个题目这一部分要看题目分析。我们设 sumsum 表示当前要用的草地数,草地数是要小于 mm 的。设 ss 表示当前奶牛的位置。因为它们是一段一段的区间构成,所以我们科已利用 whilewhile 循环来找到符合的草地(在二分midmid时)。 大体思路就是这样了,还有不懂的地方请看代码吧。

新鲜出炉的code:

C++
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define N 1000100
#define int long long
using namespace std;
int n,m,cnt,a[N],mid,ans;
struct zhs{
	int a,b;
}c[N];
bool cmp(zhs x,zhs y)
{
	return x.a<y.a;
}
bool pan(int x)
{
	int sum=1,s=c[1].a;
	for(int i=2;i<=n;i++)
	{
		if(s+x<=c[sum].b) s+=x;
		else{
			while(sum<m&&s+x>c[sum].b) 
			sum++;
			if(s+x>c[sum].b) return 0;
			if(s+x<=c[sum].a) s=c[sum].a;
			else s+=x;
		}
	}
	return 1;
}
signed main()
{
	scanf("%lld%lld",&n,&m);
	for(int i=1;i<=m;i++)
	{
		scanf("%lld%lld",&c[i].a,&c[i].b);
	}
	sort(c+1,c+m+1,cmp);
	int l,r;
	l=0;r=c[m].b;
	while(l<=r)
	{
		mid=(l+r)/2;
		if(pan(mid)){
			ans=mid;
			l=mid+1;
		}
		else
		r=mid-1;
	}
	cout<<ans<<endl;
	return 0;
}
/*
5 3
0 2
4 7
9 9
*/
/*
7 7
1 2
3 6
4 9
10 20
30 47
50 66
70 77
*/
/*
5 4
2 4
5 7
10 16
17 20
*/

如有不妥之处还请指出。

原文