当前位置: 代码迷 >> 综合 >> POJ 2456-Aggressive cows
  详细解决方案

POJ 2456-Aggressive cows

热度:30   发布时间:2023-12-01 22:10:20.0

题目传送门
Aggressive cows
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 16080 Accepted: 7693
Description

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.
Source

USACO 2005 February Gold

题意:
把C头牛放到N个带有编号的隔间里,使得任意两头牛所在的隔间编号的最小差值最大。

例如样例排完序后变成1 2 4 8 9,那么1位置放一头牛,4位置放一头牛,它们的差值为3;最后一头牛放在8或9位置都可以,和4位置的差值分别为4、5,和1位置的差值分别为7和8,不比3小,所以最大的最小值为3。

怎样完成这个牛的放置操作呢?首先对数据排序是肯定的,我们也不可能把所有可能的情况全部试一遍,因为N比较大,不太现实,我们应该想到二分法,它其实也是考虑了所有满足条件的情况,只不过它不是从头到尾的进行验证,而是从中间值开始,因为我们知道要取最大值,如果中间值满足了,就只考虑更大的值了,这样一直取中间值就可以得到结果。

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;const int maxn=1e5+100;
int locat[maxn];
int n,c;bool match(int mid)
{int last=0;for(int i=1;i<c;i++){int cnt=last+1;while(cnt<n && locat[cnt]-locat[last]<mid){cnt++;}if(cnt>=n){return false;}last=cnt;}return true;
}int main()
{while(scanf("%d%d",&n,&c)==2){for(int i=0;i<n;i++){scanf("%d",&locat[i]);}sort(locat,locat+n);int r=0,l=0x3f3f3f3f;while(l-r>1){int mid=(l+r)>>1;if(match(mid)){r=mid;}else{l=mid;}}printf("%d\n",r);}return 0;
}