๐ Electricity poles are on a horizontal line transmitting electricity through an electric wire. Each pole is located at a unique point between 0 and 1,000,000,000, inclusively, on the horizontal line. The intervals between two adjacent points are the same. The Office of Energy wants to select ๐ poles among the total of ๐ poles to install electricity amplifiers for reliable energy transmission. Considering threats of electromagnetic wave interference, the ๐ poles must be selected such that the minimum distance between two selected poles must be as large
as possible. Write a program that finds the minimum distance between two poles of the ๐ electricity poles that the Office of Energy will select.
<Requirements>
Input
The first line from the standard input has two numbers ๐ and ๐. The first number, ๐ stands for the number of electricity poles where 2 ≤ ๐ ≤ 100,000. The other number, ๐ represents the number of poles to install amplifiers for 2 ≤ ๐ ≤ ๐ ≤ 100,000.
Thereafter, ๐ lines follow, each of which contains one number that represents ๐ฅ๐, the location of an electricity pole for 1 ≤ ๐ฅ๐ ≤ 1,000,000,000. Note that these numbers are not sorted in any order.
Output
Print out one number to the standard output within 0.5 seconds.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int electricityPoles(int n, int k, vector<int> &poles)
{
int left = 1, right = poles[n - 1] - poles[0];
while (1)
{
if (left > right)
{
break;
}
int mid = (left + right) / 2;
int cnt = 1;
int start = 0;
for (int i = 1; i < n; i++)
{
if (poles[i] - poles[start] >= mid)
{
cnt++;
start = i;
}
}
if (cnt >= k)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return right;
}
int main()
{
int n, k;
vector<int> poles;
cin >> n >> k;
for (int i = 0; i < n; i++)
{
int pole;
cin >> pole;
poles.push_back(pole);
}
sort(poles.begin(), poles.end());
int ans = electricityPoles(n, k, poles);
cout << ans << endl;
}