POJ - 2456 :Aggressive cows

Posted 西北会法语

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ - 2456 :Aggressive cows相关的知识,希望对你有一定的参考价值。

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个隔断和C头牛,牛希望彼此的距离尽可能远。用二分法做。
 
源代码:
Select Code
#include<iostream>
#include<algorithm>

using namespace std;

int a[100005];

int main()
{
	int N,C;
	cin>>N>>C;
	for(int i=0;i<N;i++)
		cin>>a[i];
	sort(a,a+N);
	int low=1,hign=a[N-1]-a[0],mid,s=1,x,n=1;
	//cout<<low<<hign<<endl; 
	while(hign-low>1)
	{
		s=1;
		n=1;
		mid=(low+hign)/2;
		x=a[0]+mid;
		while(x<=a[N-1])
		{
			if(a[n++]>=x)
			{
				s++;
				x=mid+a[n-1];
			//	cout<<n-1<<endl;
			}
		}
		if(s>=C)
			low=mid;
		if(s<C)
			hign=mid;
		//cout<<s<<" "<<mid<<endl;
		//cout<<endl;
	}
	if(s>=C)
		cout<<mid<<endl;
		else
			cout<<mid-1<<endl;
	
	return 0;
}

以上是关于POJ - 2456 :Aggressive cows的主要内容,如果未能解决你的问题,请参考以下文章

POJ - 2456 Aggressive cows

POJ 2456 Aggressive cows (二分 基础)

POJ 2456 Aggressive cows

POJ 2456 Aggressive cows(二分答案)

poj2456 Aggressive cows(二分查找)

POJ 2456 Aggressive cows