Description
The annual Games in frogs’ kingdom started again. The most famous game is the Ironfrog Triathlon. One test in the Ironfrog Triathlon is jumping. This project requires the frog athletes to jump over the river. The width of the river is L (1<= L <= 1000000000). There are n (0<= n <= 500000) stones lined up in a straight line from one side to the other side of the river. The frogs can only jump through the river, but they can land on the stones. If they fall into the river, they
are out. The frogs was asked to jump at most m (1<= m <= n+1) times. Now the frogs want to know if they want to jump across the river, at least what ability should they have. (That is the frog’s longest jump distance).
Input
The input contains several cases. The first line of each case contains three positive integer L, n, and m.
Then n lines follow. Each stands for the distance from the starting banks to the nth stone, two stone appear in one place is impossible.
Output
For each case, output a integer standing for the frog’s ability at least they should have.
Sample Input
6 1 2
2
25 3 3
11
2
18
Sample Output
4
11
题意
青蛙举行了运动会,要求青蛙跳跃小河。河流宽度为 L (1<= L <= 1000000000). 河里会有 n 个石头沿着垂直于河岸的直线排成一排,青蛙以跳到石头上,然后再次跳跃。青蛙最多能够跳 m 次;现在青蛙们想知道他们最少应该有多大的跳跃能力才能够到达河对岸?
题解:
二分的经典题 最大值最小化 贪心判定+二分查询 寒假前写着毫无思路 QAQ 现在看水题一枚
AC代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6;
int arr[N];
int l, m, n;
bool check(int len)
{
int last = 0, k = 0, i = 1;
while(true) {
if(arr[i] <= last+len) i++;
else {
if(last == arr[i-1]) return false;
last = arr[i-1];
k++;
}
if(i>n+1) break;
}
k++;
if(k <= m) return true;
return false;
}
int main()
{
while(~scanf("%d%d%d",&l,&n,&m)) {
for(int i = 1;i <= n; i++) {
scanf("%d",&arr[i]);
}
int ans;
arr[n+1] = l;
sort(arr+1,arr+n+1);
int left = 1;
int right = l;
while(left <= right) {
int mid = (left+right) >> 1;
if(check(mid)) {
ans = mid; right = mid-1;
}
else left = mid+1;
}
printf("%d\n",ans);
}
return 0;
}

本文解析了一道经典的算法题目——青蛙跳河。题目要求计算青蛙至少具备多大的跳跃能力才能成功跳过宽度为L的河,河中有n个石头作为落脚点,青蛙最多能跳m次。通过二分查找结合贪心算法来求解青蛙的最小跳跃距离。
1115

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



