Aggressive cows _POJ2456

题目

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?

Input

* Line 1: Two space-separated integers: N and C

* Lines 2..N+1: Line i+1 contains an integer stall location, xi

Output

* Line 1: One integer: the largest minimum distance

Sample Input

5 3
1
2
8
4
9

Sample Output

3

Hint

OUTPUT DETAILS:

FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.

Huge input data,scanf is recommended.

 题目大意

 农夫有N间牛舍,牛舍排在一条线上,第i号牛舍在xi的位置。他的小牛彼此之间都会互相攻击。农夫为了防止牛之间互相伤害,决定要把每头牛都放在离其他牛尽可能远的牛舍。牛的数量是C,会给出n间牛舍的位置。

 算法思路:二分

 代码

 转自https://blog.csdn.net/SEVENY_/article/details/83245664

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
int n,c;
long long a[100007];
int check(long long mid)
{
	int cnt=1;      //记录牛的数量
	int crw=a[0];  //第一头牛肯定是放在最边上第一个位置。
	for(int i=1;i<n;i++)
	{
		if(a[i]-crw>=mid) //如果槽到前一头牛之间的距离大于mid,就可以将牛放到这个槽中
		{
			cnt++;
			crw=a[i];
		} 
		if(cnt>=c)return 1; 
	}
	return 0;
}
int main()
{
	scanf("%d%d",&n,&c);
	for(int i=0;i<n;i++) scanf("%lld",&a[i]);
	sort(a,a+n);
	long long l=a[0],r=a[n-1];
	while(r>l+1)
	{
		long long mid=(l+r)/2;
		if(check(mid)) l=mid;
		else r=mid;
	}
	printf("%lld\n",l);
	return 0;
} 

思路解析

我们要使每两个牛的距离尽可能大,然后找出这些距离中的最小值。也就是离得最近的两头牛之间的距离。

我们可以利用二分和贪心结合的思想,通过二分来猜测到一个值,然后进行判断,如果答案可行,则猜的距离可以再大些,如果答案不可行,则猜的距离就要再小些。

在判断答案是否可行时,可以用cnt来记录匹配到槽的奶牛数,先将第一头奶牛放在第一个槽,然后依次枚举每个槽,当枚举的槽与前一个放奶牛的槽的距离>=猜的答案时,cnt++,最后如果cnt>=牛的数量,说明这个距离可行,如果cnt<牛的数量,说明这个距离太大了。

猜你喜欢

转载自blog.csdn.net/baidu_41907100/article/details/87090506
今日推荐