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

题目:

有一个长m细木杆,有n只蚂蚁分别在木杆的任意位置。
木杆很细,不能同时经过一只蚂蚁。开始时,蚂蚁的头朝左仍是朝右是任意的,它们只会朝前走或调头,
但不会后退。当任意两只蚂蚁碰头时,两只蚂蚁会同时调头朝反方向走。假设蚂蚁们每秒钟能够走一厘米的距离。
编写程序,求全部蚂蚁都离开木杆 的最小时间和最大时间。ios

思路:

首先,讲一下思路:蚂蚁碰头后掉头,能够看成蚂蚁能够直接”穿过“对方,即蚂蚁碰头对蚂蚁运动没有影响。而后能够转换为每一只蚂蚁从初始位置直接到离开木杆的场景。
求最短期:以木杆中心为基准,左边的蚂蚁往左走,右边的蚂蚁往右走,这样子,左右两边的最短期就是所求的最短期。
求最长时间:以木杆中心为基准,左边的蚂蚁往右走,右边的蚂蚁往左走,这样子,时间就会最长web

答案:

#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;
}