您的位置:首页 > 编程语言 > C语言/C++

百度笔试编程题:爬行的蚂蚁(c++)

2016-09-13 21:35 344 查看

题目:

有一个长m细木杆,有n只蚂蚁分别在木杆的任意位置。

木杆很细,不能同时通过一只蚂蚁。开始时,蚂蚁的头朝左还是朝右是任意的,它们只会朝前走或调头,

但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟可以走一厘米的距离。

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

思路:

首先,讲一下思路:蚂蚁碰头后掉头,可以当作蚂蚁可以直接”穿过“对方,即蚂蚁碰头对蚂蚁运动没有影响。然后可以转换为每一只蚂蚁从初始位置直接到离开木杆的场景。

求最短时间:以木杆中心为基准,左边的蚂蚁往左走,右边的蚂蚁往右走,这样子,左右两边的最短时间就是所求的最短时间。

求最长时间:以木杆中心为基准,左边的蚂蚁往右走,右边的蚂蚁往左走,这样子,时间就会最长

答案:

#include <iostream>

using namespace std;

int position[100];

int main(){

int T;
scanf("%d",&T);

while (T--) {

int gan_length,ant_num,k;

while(~scanf("%d%d",&gan_length,&ant_num)){

for(int i = 0; i < ant_num; ++i){
scanf("%d",&k);
position[i] = k;
}

int speed = 1; //蚂蚁的速度
int max_time = 0; //最长时间
int min_time = 0; //最短时间

int temp_max = 0;
int temp_min = 0;

for(int i=0; i<ant_num; i++){
temp_max = 0;
temp_min = 0;

if (position[i] < gan_length / 2) //中点左边
{
temp_max = (gan_length - position[i]) / speed;
temp_min = position[i] / speed;
}
else //中点右边
{
temp_max = position[i] / speed;
temp_min = (gan_length - position[i]) / speed;
}

if (max_time < temp_max)
max_time = temp_max;
if (min_time < temp_min)
min_time = temp_min;
}

cout<<min_time<<" "<<max_time<<endl;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 笔试 百度