POJ 2456 - Aggressive cows(二分)
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.
題目大意:農夫養牛,牛喜歡打架,所以兩個牛的距離越遠越好。輸入n m,n個房間,m頭牛。依次輸入房間坐標。如何分配房間使得每個牛直接的距離都盡量大,求滿足這個條件兩個牛房間距離的最小值
Solution:先對輸入的房間坐標進行排序,然后二分查找即可。第一個房間先放一只牛,a[f]為上一頭牛所在房間坐標 如果mid為所求解 當且僅當a[i]-a[f]≥mid。如果滿足條件sum+1。如果sum大于等于m,說明mid小于所求解,更新l=mid。
#include <stdio.h> #include <string.h> #include <math.h> #include<algorithm> #include <iostream> using namespace std; const int N = 100010; int a[N]; int n, m;int judge(int mid) {int f = 0;//f為 上一頭牛 所在的房間號int sum = 1;//記錄房間總數for (int i = 1; i < n; i++){if (a[i] - a[f] >= mid)//如果mid為所求解 當且僅當a[i]-a[f]大于等于mid{f=i;sum++;}else continue;}if (sum >= m) return 1;else return 0;}int main() {scanf("%d%d", &n, &m);for (int i = 0; i < n; i++)scanf("%d", &a[i]);sort(a, a + n);int l = -1;int r = 1000000000;int ans;while (r - l >= 0){int mid = (l + r) / 2;if (judge(mid) == 1){ans = mid;l = mid;}else r = mid;if (r - l == 1) //終止條件break;}printf("%d\n", ans);return 0; }
轉載于:https://www.cnblogs.com/Chizhao/p/10439770.html
總結
以上是生活随笔為你收集整理的POJ 2456 - Aggressive cows(二分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到兔子是什么意思
- 下一篇: 梦到鸟撞玻璃有什么预兆