题目链接
题目描述
解题思路
二分答案,就是二分距离,看是否满足移动次数少于m次并且可以让最短距离最大,详细思路见代码
代码实现
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 50010;
int L, n, m, a[N],b[N];
bool check(int x)
{
//cout<<x<<endl;
int cnt = 0;
for (int i = 0; i <= (n+1); i++) b[i]=a[i];
for (int i = 1; i <= (n+1); i++) {
if (b[i] - b[i - 1] < x) {
cnt++;
b[i]=b[i-1];
//cout << "挪动了第"<<i<<"块石头" << endl;
}
}
if (cnt <= m) return true;
else return false;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> L >> n >> m;
for (int i = 1; i <= n; i++) cin >> a[i];
a[n + 1] = L;
int l = 0, r = L;
while (l < r)
{
int mid = (l + r + 1) >> 1;
if (check(mid)) l = mid;
else r = mid - 1;
}
cout << l;
return 0;
}
总结
掌握二分答案算法