-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChess-Tournament.cpp
51 lines (44 loc) · 1.73 KB
/
Chess-Tournament.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
#include <bits/stdc++.h>
using namespace std;
// Check if it is possible place c players such that the minimum distance
// between any two players is maxDis
bool check(vector<int> &positions, int n, int c, int maxDis) {
int count = 1, currPos = positions[0];
for(int i=1; i<n; i++) {
// If the distance between the current position and the next position is
// greater than maxDis, then we can place a player at the current position
if(positions[i] - currPos >= maxDis) {
count++;
currPos = positions[i];
}
}
return count >= c;
}
// Find the maximum distance between any two players such that we can place c players
int chessTournament(vector<int> &positions, int n, int c){
// Sort the positions of the players
sort(positions.begin(), positions.end());
// The minimum distance between any two players will be the distance between
// the two adjacent positions
// The maximum distance between any two players will be the distance between
// the first and the last position in the sorted order
int low = positions[1] - positions[0], high = positions[n - 1] - positions[0];
for(int i=1; i<n; i++) {
low = min(low, positions[i] - positions[i - 1]);
}
int ans = -1;
// Binary search for the maximum distance between any two players
while(low <= high) {
int mid = low + (high - low) / 2;
// If it is possible to place c players such that the minimum distance
// between any two players is mid
if(check(positions, n, c, mid)) {
ans = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
// Return the maximum distance between any two players
return ans;
}