/** */ /** * 题目: * 有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。 * 木杆很细,不能同时通过一只蚂蚁。 * 开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,但不会后退。 * 当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。 * 假设蚂蚁们每秒钟可以走一厘米的距离。 * 编写程序,求所有蚂蚁都离开木杆的最小时间和最大时间。 * * @author lupp * */ public class AntMoveQuick ... { public static void main(String[] args)...{ int[] ants = ...{3,7,11,17,23}; int length = 27; int temp = 27; int min = 0; int max = 0; //最小时间出现的情况为蚂蚁互相之间都不碰头,时间的计算方法按照离棍子中点最近的蚂蚁离开的时间 for(int i =0;i<5;i++)...{ if(Math.abs(length/2 - ants[i]) < temp)...{ temp = Math.abs(length/2 - ants[i]); min = ants[i]; } } System.out.println("最小时间 = "+min); //当两个蚂蚁相碰时调头朝相反的方向走可以等价为两个蚂蚁继续向原来自己前进的方向前进 //所以求最大时间等价为找一只蚂蚁,使它到较远端的距离最大,也就是头尾蚂蚁其中的一只。 if(length - ants[0] > ants[4]) max = length-ants[0]; else max = ants[4]; System.out.println("最大时间 = "+max); }}