poj 2456 Aggressive cows (二分)

    xiaoxiao2021-03-25  94

    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.

    刚开始把二分的最大值取错了,取成相邻区间的最大值,这样肯定不对啊,后来才想到

    #include<stdio.h> #include<string.h> #include<stdlib.h> #include<ctype.h> #include<math.h> #include<stack> #include<queue> #include<map> #include<set> #include<vector> #include<string> #include<iostream> #include<algorithm> #include<utility> #include<iomanip> typedef long long ll; const double Pi = acos(-1.0); const int N = 1e6+10, M = 1e3+20, mod = 1e9+7, inf = 2e9+10; const double e=2.718281828459 ; const double esp=1e-9; const ll INF=1e18; using namespace std; int n,c; int a[N]; int judge(int x) { int sum=0; int head=0,tail=head+1; for(int i=0;i<n;i++) { if(a[tail]-a[head]>=x) { sum++; if(sum>=c-1) return 1; head=tail;tail++; } else{ tail++; } } return 0; } int main() { while(~scanf("%d%d",&n,&c)) { for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(a,a+n); int minn=inf,maxn=0; for(int i=1;i<n;i++) { minn=min(minn,a[i]-a[i-1]); } int low=minn,high=a[n-1]-a[0]; int mid; while(low<=high) { mid=(low+high)>>1; if(judge(mid)) low=mid+1; else high=mid-1; } printf("%d\n",high); } return 0; }

    转载请注明原文地址: https://ju.6miu.com/read-33981.html

    最新回复(0)