-
Notifications
You must be signed in to change notification settings - Fork 2
/
aggressive_cows.cpp
62 lines (50 loc) · 1.32 KB
/
aggressive_cows.cpp
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
/*
Q-->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 wants 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?
*/
#include<bits/stdc++.h>
using namespace std;
bool check(int cows,long long positions[],int n,long long distance){
int count = 1;
long long last_position = positions[0];
for(int i=1;i<n;i++){
if(positions[i] - last_position >= distance){
last_position = positions[i];
count++;
}
if(count == cows){
return true;
}
}
return false;
}
int main(){
int t;
cin >> t;
while(t--){
int n,c;
cin >> n >> c;
long long positions[n];
for(int i=0;i<n;i++){
cin >> positions[i];
}
sort(positions,positions+n);
long long start = 0;
long long end = positions[n-1] - positions[0];
long long ans = -1;
while(start<=end){
long long mid = start + (end-start)/2;
if(check(c,positions,n,mid)){
ans = mid;
start = mid+1;
}else{
end = mid-1;
}
}
cout << ans <<endl;
}
return 0;
}