The Frog's Games(二分)

来源:互联网 发布:企业信息数据 编辑:程序博客网 时间:2024/06/05 08:58
Problem 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 2225 3 311 218
 

Sample Output
411
 
先讲下大概题意,一只青蛙从河岸要跳到对岸去,河的宽度是L,两岸间有n块石头排成一列相当于桥,青蛙的每一次跳跃必须落在石头上或者是岸上,最多只能跳m次,题目给出从出发点(岸上)到n块石头的距离,要求输出青蛙在满足上述要求的条件下要到达对岸,最少的跳跃能力是多远,即青蛙以每次跳ans远的距离跳跃,最后需要跳x次才能到达对岸,那么我们要尽量地使x接近于m且x<=m,求出此时的ans值。

先求出两相邻石头之间的距离的最大值MAX,MAX是青蛙在跳跃次数无限制的情况下的最小跳跃能力(如果这个都不满足,青蛙根本都过不了河),然后青蛙的能力也不用太强,最小跳跃能力最多是L,因此以[MAX,L+1)(也可以是[MAX,L],个人习惯使用左闭右开区间)作为二分搜索的区间,根据具有的能力计算出所需跳跃次数TIMES和m比较,不断二分缩小搜索范围,最后找到一个最小的能力值使TIMES<=m且TIMES接近于m。


#include <stdio.h>  #include <string.h>  #include <iostream>  #include <algorithm>    using namespace std;const int maxn =  500005;int num[maxn];int L,n,m;bool check(int mid)//判断当前mid是否可以在m步内走到河流{    if(mid < num[0])return false;    int dis = 0;    int k = m;    for(int i = 1; i <= n; i ++ )    {        if(mid < num[i] - dis && mid >= num[i-1]-dis) { k -- ; dis=num[i-1];}                                        if(k<=0) return false;        if(mid < num[i]-dis)return false;//跳了一步后  跳不到下一步就不行    }      return true;   }int main(){    int i;    while(~scanf("%d %d %d",&L,&n,&m))    {        for( i = 0; i < n; i ++)scanf("%d",&num[i]);        sort(num,num+n);        num[n] = L;        int l = 0,r = L;        int ans  = 0;        while(l<= r)        {            int mid = (l+r)>>1;            if(check(mid))            {                ans = mid;                r = mid - 1;            }            else l = mid + 1;        }        printf("%d\n",ans);    }    return 0;}


0 0
原创粉丝点击