Aggressive cows
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.
Source
题目类型:二分
算法分析:首先将距离按照从小到大的顺序排列,二分枚举距离,然后按照该距离将牛分配到这些牛棚中,看能不能将牛全部安排好,如果能则将距离提高,继续枚举;否则将距离减小,继续枚举
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
#include <set> #include <bitset> #include <list> #include <map> #include <stack> #include <queue> #include <deque> #include <string> #include <vector> #include <ios> #include <iostream> #include <fstream> #include <sstream> #include <iomanip> #include <algorithm> #include <utility> #include <complex> #include <numeric> #include <functional> #include <cmath> #include <ctime> #include <climits> #include <cstdarg> #include <cstdio> #include <cstdlib> #include <cstring> #include <cctype> #include <cassert> #define lson rt << 1, l, m #define rson rt << 1 | 1, m + 1, r using namespace std; const int INF = 0x7FFFFFFF; const double EPS = 1e-10; const double PI = 2 * acos (0.0); const int MOD = 7; const int maxn = 166000 + 66; int ans[maxn]; int n, c; bool Solve (int val) { int i, sum = 1, p = ans[0]; for (i = 1; i < n; i++) { if (ans[i] - p >= val) { sum++; p = ans[i]; } } if (sum >= c) return false; return true; } int main() { // freopen ("aaa.txt", "r", stdin); while (scanf ("%d%d", &n, &c) != EOF) { int i; for (i = 0; i < n; i++) scanf ("%d", &ans[i]); sort (ans, ans + n); int L = 1, R = ans[n-1], mid; while (L <= R) { mid = (L + R) >> 1; if (Solve (mid)) R = mid - 1; else L = mid + 1; } printf ("%d\n", R); } return 0; } |