百度面试题[转自CSDN]

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

#include <iostream>

#include <string>

#include <cmath>

using std::cout;

using std::endl;

#define SLEN 27

int getL(int ad)

{

    return abs(SLEN-ad)>ad ? abs(SLEN-ad) : ad;

};

int getS(int ad)

{

    return SLEN-getL(ad);

};

int main(void)

{

    int ads[]={3,7,11,17,23};

    int L=0,S=0;

    for(int i=0;i<5;++i)

   {

      if (L<getL(ads[i])) L=getL(ads[i]);

      if (S<getS(ads[i])) S=getS(ads[i]);

   };

   cout<<"最长所需"<<L<<"秒。\n最短所需"<<S<<"秒。"<<endl; return 0;

}

原文地址:https://www.cnblogs.com/chenqingwei/p/1581511.html