题意:
青蛙过河,河中有一定数量的石墩,并规定能跳的步数,求可能的最小步长过河。
思路:
最大值最小化问题一般用二分来求解。先将石墩距离起始点的距离排序,然后通过二分枚举求得是否存在一个m值(0~L),使得青蛙可以走过所有的石墩。如果存在且小于M,则记录满足条件的最小值,直至当前点到达n-1为止。
AC代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cstdlib>
using namespace std;
typedef long long ll;
const int N = 500005;
int len, n, m;
int pos[N];
bool judge(int x) {
int next, cur = 0;
for(int i = 1; i <= m; i++) {
if(pos[cur+1] - pos[cur] > x) return false;
next = cur+1;
while(pos[next] - pos[cur] <= x) {
if(next == n-1) return true;
next++;
}
cur = next-1;
}
return false;
}
int main() {
while(scanf("%d%d%d", &len, &n, &m) != EOF) {
for(int i = 0; i < n; i++) {
scanf("%d", &pos[i]);
}
pos[n++] = 0; pos[n++] = len;
sort(pos, pos+n);
int L = 1, R = len;
while(L < R) {
int M = (L+R)/2;
if(judge(M)) R = M;
else L = M+1;
}
printf("%d\n", R);
}
return 0;
}
本文介绍了一种解决青蛙过河问题的方法,通过二分查找确定最小步长,使青蛙能够跨越不同位置的石墩过河。文章提供了完整的AC代码实现。
1115

被折叠的 条评论
为什么被折叠?



