2456:Aggressive cows(二分查找)
1 #include <bits/stdc++.h> 2 using namespace std; 3 int N,C; 4 int a[100000]; 5 int fun(int d) { 6 int temp=a[0], k=1; 7 for(int i=1; i<N; i++) { 8 if(a[i]-temp>=d) { 9 temp=a[i]; 10 k++; 11 } 12 } 13 if(k>=C)return 1; 14 else return -1; 15 } 16 int main() { 17 while(cin>>N>>C) { 18 int ans=0; 19 for(int i=0; i<N; i++) { 20 cin>>a[i]; 21 } 22 sort(a,a+N); 23 int left=1,right=a[N-1]-a[0]; 24 while(left<=right){ 25 int mid=left+(right-left)/2; 26 if(fun(mid)>0){ 27 left=mid+1; 28 } 29 else right=mid-1; 30 } 31 cout<<left-1<<endl; 32 } 33 return 0; 34 }
2456:Aggressive cows
- 总时间限制:
- 1000ms
- 内存限制:
- 65536kB
- 描述
- 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? - 输入
- * Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi - 输出
- * Line 1: One integer: the largest minimum distance
- 样例输入
-
5 3 1 2 8 4 9
- 样例输出
-
3
- 提示
- 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. - 来源
- USACO 2005 February Gold
- 直接暴力会超时。所以还是二分查找。二分法的运用要注意边界条件的判断。有时候懒得去判断,直接提交测试,不外乎是否取等于号或者边界是否加一。
越努力越幸运