P6281 [USACO20OPEN] Social Distancing S
Microperson · · 题解
题目链接
思路:
当我们看到:
其中D为最近的两头奶牛之间的距离。请帮助奶牛们求出D的最大可能值。
也就是说有N头奶牛放到有草的区间中,使得两头牛之间最小的距离最大。 这就很显而易见了,那就是二分答案了。
这N头牛是要全部放进去的,所以我们需要一层循环处理处每头牛要在的位置,判断当前的
while(l<=r)
{
mid=(l+r)/2;
if(pan(mid)){
ans=mid;
l=mid+1;
}
else
r=mid-1;
}
cout<<ans<<endl;
}
这里的边界不是一定的每个题目对应关系可能不同。
接下来就是二分答案了,也就是神奇的
新鲜出炉的code:
#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
*/
如有不妥之处还请指出。