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
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
- Poj 2456 Aggressive cows
- POJ 2456 Aggressive cows
- poj 2456 Aggressive cows
- poj 2456 Aggressive cows
- POJ-2456-Aggressive cows
- POJ 2456 Aggressive cows
- POJ-2456 Aggressive cows
- poj 2456 Aggressive cows
- POJ 2456 Aggressive cows
- POJ 2456 Aggressive cows
- poj 2456 Aggressive cows
- POJ 2456 Aggressive cows
- POJ 2456 Aggressive cows
- POJ-2456 Aggressive cows
- POJ-2456Aggressive cows
- POJ 2456 - Aggressive cows
- POJ 2456 Aggressive cows
- poj 2456 Aggressive cows
- LeetCode-337. House Robber III
- oracle sqlldr控制文件模板
- GraphicsView 使用时,程序死掉总结
- HDU 4699
- iOS网络编程 - 6
- POJ 2456Aggressive cows
- linux sort 命令详解
- 4月28--30日:一起去北展揭开电信网络诈骗的神秘面纱
- SQL中 decode()函数简介
- 奇异值分解(SVD) --- 几何意义
- hdu 1285 确定比赛名次 //简单拓扑排序
- 详解图像直方图均衡化原理,附MATLAB、C、C++源码
- onConfigurationChanged的作用
- Cloneable接口和Object的clone()方法