北京大学acm二分题 农场牛栏间隔 最大最小问题


Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).

His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
输入
* Line 1: Two space-separated integers: N and C

* Lines 2..N+1: Line i+1 contains an integer stall location, xi
输出
* Line 1: One integer: the largest minimum distance
样例输入
5 3
1
2
8
4
9
样例输出
3

方法一:按照隔间进行枚举,即两个隔间之间的距离满足条件的就保留

#include<algorithm>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,c,a[100005];
int check(int d)
{
	int cow=1,pre=0;
	for(int i=1;i<n;i++)
	{
		if(a[i]-a[pre]>=d)
		{
			cow++;//能够放进去的牛的个数
			pre=i;
		}
		
	}
	if(cow>=c)
		return 1;
		else
		return 0;
}
int main()
{
	memset(a,0,sizeof(int));
	scanf("%d%d",&n,&c);
	for(int i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	int l,r,mid,ans=0;
	sort(a,a+n);
	l=a[0];
	r=a[n-1];
	while(l<=r)
	{
		mid=(l+r)/2;
		if(check(mid))
		{
		    ans=mid;
			l=mid+1;
		}
		
		else
		r=mid-1;
	}
	cout<<ans<<endl;
	
}

方法二:按照牛的个数进行枚举,即看看在mid这个间隔下是不是能把所有的牛都放进去

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int N ,C, a[100005];
int check(int d)
{
	int pre=0,j;
	for(int i=1;i<C;i++)//C为牛的个数
	{
	j=pre+1;
	while(j<N&&(a[pre]+d)>a[j])
	j++;
	if(j>=N)
	return 0;
	pre = j;
	} 
	return 1;
}
int main()
{
memset(a,0,sizeof(int));
	scanf("%d%d",&N,&C);
	for(int i=0;i<N;i++)
	{
		scanf("%d",&a[i]);
	 } 
	 sort(a,a+N);
	 int l,r,mid,ans=0;
	 l = a[0];
	 r = a[N-1];
	 while(l<=r)
	 {
	 	 mid=(l+r)/2;
	 if(check(mid))
	 {
	 	ans=mid;
	 	l=mid+1;
	 }
	 else
	 r=mid-1;
	 }
	printf("%d",ans);
 } 

猜你喜欢

转载自blog.csdn.net/adiamond1/article/details/81452855