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);
}
}
答:
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);
}
}