杭电oj 4004---The Frog Games java解法

import java.util.Arrays;

import java.util.Scanner;

//杭电oj 4004

//解题思路:利用二分法查找,即先选取跳跃距离的区间,从最大到最小,

//然后去中值,并依次到judgeHigh函数判断是否满足条件,然后逐步逼近最终答案

public class Main {

    public static void main(String[] args) {

        Scanner in=new Scanner(System.in);

        while (in.hasNext()) {

            int L=in.nextInt();

            int n=in.nextInt();

            int m=in.nextInt();

            int[] stones=new int[n];

            for (int i = 0; i < n; i++) {

                stones[i]=in.nextInt();

            }    

            int[] p=new int[n+2];

            p[0]=0;

            p[n+1]=L;

            for (int i = 0; i < stones.length; i++) {

                p[i+1]=stones[i];

            }

            Arrays.sort(p);

            int left=L/m;

            int right=L;

            while (left<=right) {

                int mid=left+(right-left)/2;

                if (judgeHigh(p,mid,m)) {

                    right=mid-1;//取小

                }else {

                    left=mid+1;//取大

                }

            }

            System.out.println(left);

        }

      

        

    }

    public static boolean judgeHigh(int[] d,int max,int m) {//判断中值是否大于最小可跳距离

        int last=d[0];

        int count=0;//jump's nums of times

        for (int i = 1; i <d.length; i++) {

            if (d[i]-d[i-1]>max) {//如果大于最大值,说明这个距离不是最远距离,得增大

                return false;

            }

            if (d[i]-last>max) {//中间隔几个石头判断是否大于最大值,如果大于,则取更靠后的石头,否则就落在前一个石头上

                count++;

                last=d[i-1];

                if (count>=m) {

                    return false;

                }

            }

        }

        return true;

    }

}

posted @ 2019-03-16 21:26  GavinYGM  阅读(181)  评论(0编辑  收藏  举报