北京大学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);
 } 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值