蚂蚁过桥

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

求所有蚂蚁都离开木杆的最小时间和最大时间,编写程序验证。 

#define ANT_NUM 5
#define STATUS_NUM 32 /* 1<<ANT_NUM */

struct
{
 int pos;  /* position of ant */
 int dir;  /* direction of ant, with value -1 or 1 */
 int time; /* time taken to pass */
}ant[ANT_NUM];

/* each ant has a certain direction at a time, either left or right.
   a bit with value 0 or 1 represents this status.
   5 ants have five status-bit.
*/
int status[ANT_NUM]={1,2,4,8,16};

/* the first position of ants */
int pos[ANT_NUM]={3,7,11,17,23};

/* reset all ants status according to parameter s */
void init(int s)
{
 int i;

 printf("/n/nstatus %2d: ant, pos, dir/n", s);
 for (i=0; i<ANT_NUM; i++)
 {
  ant[i].dir = (status[i]&s ? 1 : -1);
  ant[i].time = 0;
  ant[i].pos = pos[i];
  printf("          %3d  %3d  %3d/n",
   i, ant[i].pos, ant[i].dir);
 }
 printf("/n");
}

/* return the time taken to get all ants pass */
int run()
{
 int antleft=ANT_NUM;
 int max = 0;
 int j;

 while (antleft)
 {
  for (j=0; j<ANT_NUM; j++)
  {
   /* ant[j] has already passed? */
   if (ant[j].pos<1 || ant[j].pos>26)
    continue;

   /* ant[j] moves one step */
   ant[j].pos+=ant[j].dir;
   ant[j].time++;

   /* ant[j] has already reached now? */
   if (ant[j].pos<1 || ant[j].pos>26)
   {
    printf ("Ant[%d] reachs %2d at %2d./n",
     j,ant[j].pos,ant[j].time);

    if (ant[j].time > max)
     max = ant[j].time;

    antleft--;
   }
  }

  for (j=1; j<ANT_NUM; j++)
  {
   /* for each ant doesn't pass, check collision */
   if (ant[j-1].pos>0 && ant[j-1].pos<27 &&
    ant[j].pos>0 && ant[j].pos<27 &&
    ant[j-1].pos==ant[j].pos)
    {
     /* reset the two ants' direction */
     ant[j].dir*=-1;
     ant[j-1].dir*=-1;
    }
  }
 }

 return max;
}

void main()
{
 int i,c;
 int min=32767,max=0;

 clrscr();

 /* enumerate all status of ants */
 for (i=0; i<STATUS_NUM; i++)
 {
  init(i);
  c=run();

  if (max < c)
   max = c;
  if (min > c)
   min = c;
 }

 printf("/nmax: %d, min: %d", max, min);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值