백준
1. 이진탐색 (파라메트릭 서치)
n, c = list(map(int, input().split()))
array = [int(input()) for _ in range(n)]
array.sort()
start = 1
end = array[-1] - array[0]
result = 0
while(start <= end):
mid = (start + end) // 2
value = array[0]
count = 1
for i in range(1, n):
if array[i] >= value + mid:
value = array[i]
count += 1
if count >= c:
start = mid + 1
result = mid
else:
end = mid - 1
print(result)
2. C++
#include <bits/stdc++.h>
using namespace std;
int n, c;
vector<int> arr;
int main() {
cin >> n >> c;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
arr.push_back(x);
}
sort(arr.begin(), arr.end());
int start = 1;
int end = arr[n - 1] - arr[0];
int result = 0;
while (start <= end) {
int mid = (start + end) / 2;
int value = arr[0];
int cnt = 1;
for (int i = 1; i < n; i++) {
if (arr[i] >= value + mid) {
value = arr[i];
cnt += 1;
}
}
if (cnt >= c) {
start = mid + 1;
result = mid;
}
else {
end = mid - 1;
}
}
cout << result << '\n';
}