• Algs4-1.4.24扔鸡蛋


    1.4.24扔鸡蛋。假设你面前有一栋N层的大楼和许多鸡蛋,假设将鸡蛋从F层或者更高的地方扔下鸡蛋才会摔碎,否则则不会。首先,设计一种策略来确定F的值,其中扔 ~logN次鸡蛋后摔碎的鸡蛋数量为~logN,然后想办法将成本降低到~2logF。
    答:

    图片

    图片



    public class E1d4d24
    {
        public static void rankLgN(int N,int f)
        {
           if(N<1) return;
           if(f<1) return;
           if (f>N) return;
           //
            int lo=1;
            int hi=N;
            int mid=1;
            int runTimes=0;
            while(lo<hi)
            {
                mid=(lo+hi)/2;
                if(mid>=f)
                    hi=mid;
                else
                    lo=mid+1;
                runTimes++;
            }
            StdOut.printf("Algs lgN runTimes=%d,lo=%d ",runTimes,lo);
        }
       
         public static void rank2LgF(int N,int f)
        {
           if(N<1) return;
           if(f<1) return;
           if (f>N) return;
           //
            int floor=1;
            int  runTimes=0;
            while(floor<f)
            {
                floor=2*floor;
                 runTimes++;
            }
            //
            int lo=floor/2;
            int hi=floor;
            int mid=lo;
            while(lo<hi)
            {
                mid=(lo+hi)/2;
                 if(mid>=f)
                    hi=mid;
                else
                    lo=mid+1;
                 runTimes++;
            }
            StdOut.printf("Algs 2lgF runTimes=%d,lo=%d ",runTimes,lo);
        }
       
        public static void main(String[] args)
        {
            int N=Integer.parseInt(args[0]);
            int f=Integer.parseInt(args[1]);
            rankLgN(N,f);
            rank2LgF(N,f);
        }
    }
  • 相关阅读:
    超级变态之access查询
    计算机安全病毒问题汇集(转自华军)
    Avast I Love You
    Windows2003 3389端口修改
    希捷 250G 7200.10 8M(串口/5年盒)(买硬盘了~~~)
    DataTable 中Remove方法的使用
    我的主板(p5pl2e)
    冼东妹(为奥运冠军名字作诗)
    李彦宏告诫年轻人:向前看两年
    郭文珺(为奥运冠军名字作诗)
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854466.html
Copyright © 2020-2023  润新知