POJ - 2456 Aggressive cows(二分+贪心)

Posted SomnusMistletoe

tags:

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

题意:把c个牛分进n个摊位,摊位位置已知,所有摊位分布在0 <= xi <= 1,000,000,000,问两头牛间最小距离的最大值。

分析:找所有最小距离取个最大的。所以二分找这个最小的距离,这个最大的最小距离是二分的分界线。贪心来判断当前的最小距离是否能安排下所有的牛。

#pragma comment(linker, "/STACK:102400000, 102400000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
typedef long long ll;
typedef unsigned long long llu;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const ll LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const double eps = 1e-8;
const int MAXN = 100000 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[MAXN];
int n, c;
bool judge(int x){
    int cnt = 1;
    int st = a[0];
    for(int i = 1; i < n; ++i){
        if(a[i] - st >= x){
            ++cnt;
            st = a[i];
        }
        if(cnt == c) return true;
    }
    return false;
}
int solve(){
    int l = 1, r = 1e9;
    while(l < r){
        int mid = l + (r - l + 1) / 2;
        if(judge(mid)) l = mid;
        else r = mid - 1;
    }
    return l;
}
int main(){
    while(scanf("%d%d", &n, &c) == 2){
        memset(a, 0, sizeof a);
        for(int i = 0; i < n; ++i){
            scanf("%d", &a[i]);
        }
        sort(a, a + n);
        int ans = solve();
        printf("%d\n", ans);
    }
    return 0;
}

 

以上是关于POJ - 2456 Aggressive cows(二分+贪心)的主要内容,如果未能解决你的问题,请参考以下文章

POJ - 2456 Aggressive cows

POJ 2456 Aggressive cows (二分 基础)

POJ 2456 Aggressive cows

POJ 2456 Aggressive cows(二分答案)

POJ 2456 Aggressive cows

[POJ2456]Aggressive cows