一道百度试题蚂蚁过竿

来源:互联网 发布:手机淘宝标题在哪设置 编辑:程序博客网 时间:2024/05/02 04:55

 

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

解:
既然两只蚂蚁碰头后,速度不变,只改变方向,那么不妨把问题转化为两个蚂蚁碰头后相互穿过对方。
所以最大的时间为左端的蚂蚁到右端的时间和右端的蚂蚁到左端的时间两者中的最大值。即max(27-3,23)=24
最小时间即为中间的那只蚂蚁到某一端的最小时间,即为min(11,27-11)=11

 

 程序如下:但是程序确实用穷举法的

#include<stdio.h>#include<math.h>#define ANT_NUM 5int MatrixSum(int array[],int arraysize){ int sum=0; for(int i=0;i<arraysize;i++)       if(array[i]!=-1)             sum+=array[i]; return sum;}int TimeCosume(int loc[],int dic[],int bamboolength){ int consume=0; while(MatrixSum(loc,ANT_NUM)!=0){  consume++;  for(int i=0;i<ANT_NUM;i++)    loc[i]+=dic[i];  for(int j=0;j<ANT_NUM;j++){   if(loc[j]==0||loc[j]==bamboolength){            dic[j]=0;            loc[j]=-1;}   for(int k=j+1;k<ANT_NUM;k++){    if(loc[j]-loc[k]==0){    dic[j]*=-1;    dic[k]*=-1; }}}} return consume;}void renew(int standard[],int copy[],int dic[],int n){ int j=0; for(int k=0;k<ANT_NUM;k++)        dic[k]=-1;for(int i=0;i<ANT_NUM;i++ ) copy[i]=standard[i];while(n!=0){  dic[j]+=(n%2)*2;     n=n/2;     j++;}}void MaxMinConsume(int loc[],int bamboolength){ int locTemp[5]; int dic[5]={-1}; int Max_consume=0; int Min_consume=ANT_NUM*bamboolength;//because many computer can't support the syntax INT_MAX so that we should use the max time consume for(int i=0;i<pow(2,ANT_NUM);i++){     int temp=0;  renew(loc,locTemp,dic,i);     temp=TimeCosume( locTemp, dic,bamboolength);  if(temp>Max_consume)  Max_consume=temp;  if(temp<Min_consume)  Min_consume=temp;} printf("the Max time consume is %d\n",Max_consume/2); printf("the MIn time consume is %d\n",Min_consume/2);} int  main(){int bamboolength; int loc[5]; printf("\n          ^_^welcome to wuhan university^_^\n\n"); printf("please input the ants location\n"); for(int i=0;i<5;i++){         printf("the %dth ant's location:",i+1);         scanf("%d",&loc[i]);         loc[i]*=2;         printf("\n");} printf("\n\nplease input the length of bamboo:"); scanf("%d",&bamboolength); bamboolength*=2; printf("\n"); MaxMinConsume (loc,bamboolength); printf("\n          ^_^welcome to wuhan university^_^\n\n"); getchar(); getchar(); return 0;}


 

原创粉丝点击