-
Notifications
You must be signed in to change notification settings - Fork 6
/
AggressiveCows.cpp
58 lines (45 loc) · 1.08 KB
/
AggressiveCows.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
#include <iostream>
#include <vector>
#include <unistd.h>
#include <algorithm>
using namespace std;
long long binarySearch(vector<long long>& arr, long long nCows);
long long placeCows(vector<long long>& arr, long long distance);
int main() {
long long T;
cin >> T;
while(T--) {
long long N, C;
cin >> N >> C;
vector<long long> arr(N);
for(long long i = 0; i < N; i++)
cin >> arr[i];
sort(arr.begin(), arr.end());
cout << binarySearch(arr, C) << endl;
}
return 0;
}
long long binarySearch(vector<long long>& arr, long long nCows) {
long long start = 1, end = arr.back()+1;
while(start+2 <= end) {
long long mid = start + (end-start)/2;
if(placeCows(arr, mid) >= nCows) {
start = mid;
}
else {
end = mid;
}
}
return start;
}
long long placeCows(vector<long long>& arr, long long distance) {
long long nCows = 1, curStall = 1, lastPlaced = 0;
while(curStall < arr.size()) {
if(arr[curStall]-arr[lastPlaced] >= distance) {
nCows++;
lastPlaced = curStall;
}
curStall++;
}
return nCows;
}