POJ 2456Aggressive cows

来源:互联网 发布:电子样本制作软件 编辑:程序博客网 时间:2024/05/01 20:57
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


这一题确定最大的距离使用二分搜索来试值的。然后用贪心算法判断是否满足。不断的缩小范围,时间复杂度为O(n*logn);


AC代码:


# include <cstdio># include <algorithm>using namespace std;int a[100010];int n, c;int judge(int d){int cur1=1, cur2=2;int ans=1;while(ans<c&&cur2<=n){if(a[cur2]-a[cur1]>=d){ans++;cur1=cur2;cur2++;}else{cur2++;}}if(ans<c){return 0;}return 1;}int main(){int i, j, k; int left, right, mid, ans;while(scanf("%d%d", &n, &c)!=EOF){for(i=1; i<=n; i++){scanf("%d", &a[i]);}ans=1;sort(a+1, a+n+1);left=1;right=a[n];while(left<=right){mid=(left+right)/2;if(judge(mid)){ans=mid;left=mid+1;}else{right=mid-1;}}printf("%d\n", ans);}return 0;}



0 0
原创粉丝点击