有一根27厘米的细木杆,在第3厘米、7厘米、11厘米、17厘米、23厘米这五个位置上各有一只蚂蚁。木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。编写程序,求所有蚂蚁都离开木杆的最小时间和最大时间。

分析:

1,求所有蚂蚁都离开木杆的最小时间和最大时间,即最后一只蚂蚁离开木杆的最小时间和最大时间。

2,两只蚂蚁相遇调头,由于蚂蚁的速度都是一样的,调头并没有改变最后一只蚂蚁离开木杆的时间。于是可以将“两只蚂蚁相遇掉头”看作“两只蚂蚁擦肩而过”,这样理解就更简单了。

3,所有蚂蚁离开木杆的最小时间就是所有(本题为5只)蚂蚁分别离开木杆的最小时间中的最大值;同理,所有蚂蚁离开木杆的最大时间就是对应的最大时间中的最大值。(最大值保证了最后一只蚂蚁离开杆)

 

方法:

1,求最大时间。

        public int GetMaxTime()
        {
            int length = 27; //木杆的长度
            int speed = 1;//蚂蚁的爬行速度
            int[] pos = new int[5] { 3, 7, 11, 17, 23 };//蚂蚁所在的位置
            int[] distance = new int[5];//5只蚂蚁爬行对应的最大距离
            int maxLenth = 0;//5只蚂蚁爬行对应的最大距离中的最大值
            for (int i = 0; i < 5; i++)
            {
                //杆两端中最远的距离为蚂蚁爬行的最大距离
                if (pos[i] <= length / 2)
                {
                    distance[i] = length - pos[i];
                }
                else
                {
                    distance[i] = pos[i];
                }
                if (maxLenth < distance[i])
                {
                    maxLenth = distance[i];
                }
            }
            return maxLenth / speed;
        }

2,求最小时间。

        public int GetMinTime()
        {
            int length = 27; //木杆的长度
            int speed = 1;//蚂蚁的爬行速度
            int[] pos = new int[5] { 3, 7, 11, 17, 23 };//蚂蚁所在的位置
            int[] distance = new int[5];//5只蚂蚁爬行对应的最小距离
            int maxLenth = 0;//5只蚂蚁爬行对应的最小距离中的最大值
            for (int i = 0; i < 5; i++)
            {
                //杆两端中最近的距离为蚂蚁爬行的最小距离
                if (pos[i] <= length / 2)
                {
                    distance[i] =  pos[i];
                }
                else
                {
                    distance[i] =length- pos[i];
                }
                if (maxLenth < distance[i])
                {
                    maxLenth = distance[i];
                }
            }
            return maxLenth / speed;
        }

  

 posted on 2015-09-06 16:45  会飞的金鱼  阅读(2000)  评论(0)    收藏  举报