蚂蚁爬杆问题

来源:互联网 发布:windows开启443端口 编辑:程序博客网 时间:2024/04/27 20:03

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

解决方法:

所有蚂蚁都离开木杆的最小时间相当于每只蚂蚁离开的最小值的最大值,即:

min=max(min(3),min(7),min(11),min(27-17),min(27-23));

所有蚂蚁都离开的最大时间为:

max=max(max(27-3),max(27-7),max(27-11),max(17),max(23));

下面给出两种解法代码如下:

#include <stdio.h>void CalcTime1(double Length,double *xPos,int num,double Speed,double *min,double *max){double TotalTime=Length/Speed;int i;double currentMax,currentMin;*max = 0;*min = 0;for (i = 0;i < num;i++){if (xPos[i] > Length/2){currentMax = xPos[i];}else{currentMax = (Length-xPos[i])/Speed;}currentMin = TotalTime-currentMax;if (*max < currentMax){*max = currentMax;}if (*min < currentMin){*min = currentMin;}}}void CalcTime2(double Length,double *xPos,int num,double Speed,double *min,double *max){double currentMin;double currentMax;int i;currentMin = Length;currentMax = Length;for (i = 0;i < num;i++){if ((xPos[i] >= Length/2 && currentMin > (xPos[i]-Length/2)) || (xPos[i] <= Length/2 && currentMin > (Length/2-xPos[i]))){if ((xPos[i]-Length/2)>=0){currentMin = xPos[i]-Length/2;*min = (Length-xPos[i])/Speed;}else if((xPos[i]-Length/2)<= 0){currentMin = Length/2-xPos[i];*min = xPos[i]/Speed;}}if (currentMax > (Length-xPos[i]) || currentMax > xPos[i]){if (xPos[i] >= Length/2){currentMax = Length-xPos[i];*max = xPos[i]/Speed;}else{currentMax = xPos[i];*max = Length-xPos[i]/Speed;}}}}int main(){double Length=27.0;int num = 5;double Speed = 1;double min;double max;double xPos[]={3,7,11,17,23};CalcTime1(Length,xPos,num,Speed,&min,&max);printf("方法1,计算结果:\n");printf("min = %f,max = %f\n",min,max);CalcTime2(Length,xPos,num,Speed,&min,&max);printf("方法2,计算结果:\n");printf("min = %f,max = %f\n",min,max);system("pause");return 0;}



0 0