Aggressive cows
| Time limit:1000 ms |
|
Memory limit:65536 K |
| Total submissions:6372 |
|
Accepted:3181 |
Description
Farmer John has built a new long barn, with N (2 <= n <= 100,000) stils. the stallare 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 stils, 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 312849
Sample output
3
Question:
There are n cattle houses, I is at the position of Xi, and m cattle are at the same time. Place the M cattle in the barn to maximize the distance between each cow.
Ideas:
Because the distance between each ox cannot be determined directly, we can consider finding the minimum distance between all cows, use a binary search from large to small to find the result that satisfies the CRT <n & X [CRT]-X [last]> D, in this case, X [CRT]-X [last] indicates the fourth CRT barn.
Distance from the previous cattle can be placed, if greater than D, it means that the CRT or crt-1 position of the cattle in the critical point, can be placed cattle, if less than D indicates that not up to the critical point, CRT ++ to continue searching.
The Code is as follows:
#include<iostream>#include<algorithm>using namespace std;const long MAXN=100000;const long INF=1000000000;long X[MAXN];long N,M;int Tdfs(long d){long last=0;for(int i=1;i<M;i++){long crt=last+1;while(crt<N&&X[crt]-X[last]<d){crt++;}if(crt==N)return 0;last=crt;}return 1;}int main(){int i;long lb,ub,mid;while(cin>>N>>M){lb=0,ub=INF;for(i=0;i<N;i++)cin>>X[i];sort(X,X+N);while(ub-lb>1){mid=(lb+ub)/2;if(Tdfs(mid))lb=mid;elseub=mid;}cout<<lb<<endl;}return 0;}
You do not need to use long or _ int64. The long data type is sufficient. The maximum length is 2.1 billion +. In addition, pay attention to the failure condition "If (CRT = N) return 0;". When 1 is returned, lB = mid increases the D value, and vice versa decreases the D value.
Poj 2456 aggressive cows (maximizing the minimum value of Binary Search)