思路:用二分,每次二分间距,判断需要的组数是否>k。
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int L, n, k;
int a[N];
bool check(int p)
{ // 看此时的间距所用的警力数满不满足<=k
int cnt = 0;
for (int i = 2; i <= n; i++)
{
int temp = a[i] - a[i - 1];
int a1 = temp / p; // 需要多少组
int a2 = temp % p;
if (a1 > 0)
{
if (a2 > 0)
{
cnt += a1;
}
else
{ // 无余数,例4/2=2,只需2-1=1组即可
cnt += a1 - 1;
}
}
}
if (cnt > k)
return false;
return true;
}
int main()
{
cin >> L >> n >> k;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
}
sort(a + 1, a + n + 1);
int l = 1, r = L, mid;
while (l <= r)
{
mid = (l + r) / 2;
if (check(mid))
{
r = mid - 1;
}
else
l = mid + 1;
}
cout << l;
}
下面是错误代码:(有没有好心人告诉我为什么错了/(ㄒoㄒ)/~~)
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int l, n, k;
priority_queue<int, vector<int>, less<int>> q;//大根堆
int b[N];
int main()
{
cin >> l >> n >> k;
for (int i = 1; i <= n; i++)
{
cin >> b[i];
}
sort(b + 1, b + n + 1); // 升序
for (int i = 2; i <= n; i++)
{
q.push(b[i] - b[i - 1]);
}
for (int i = 0; i < k; i++)
{
int pp = q.top();
q.pop();
int uu = pp / 2;
q.push(uu);
q.push(pp - uu);
}
cout << q.top();
}