POJ 2456_Aggressive cows

题意:

给定N个位置,把C头牛分别放入,求相邻两头牛的最大距离。

分析:

即为求两头牛之间最小距离的最大值。二分搜索答案。

代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxn = 100005, INF =0x3fffffff;
typedef long long ll;
int x[maxn];
int N, C;
int judge(int a)
{
    int last = 0, cnt  = 1, tmp;
    while(last < N - 1){
        tmp = last + 1;
        while(x[tmp] - x[last] < a) tmp++;
        if(tmp < N) cnt++;
        if(cnt >= C) return 1;
        last = tmp ;
    }
     return 0;
}
int main (void)
{
    scanf("%d%d",&N,&C);
    for(int i = 0; i < N; i++) scanf("%d",&x[i]);
    sort(x, x + N);
    int l = 0, r = INF, mid;
    while(l<r-1){
        mid = l + (r - l)/2;
        if(judge(mid)) l  = mid;
        else r = mid;
    }
    printf("%d\n",l);
}

你可能感兴趣的:(POJ 2456_Aggressive cows)