poj1852 Ants 窮竭搜索

An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.

題意:講的是n個螞蟻在一個長度爲L的竿子上爬行。當螞蟻爬到竿子終點的時候就會掉落。兩隻螞蟻相遇的時候只能各自反爬回去,求問所有螞蟻下落竿子的最短時間和最長時間。

題解:可以假設螞蟻是可以相遇的。這樣不管螞蟻的方向都可以走到尾。我們用現在螞蟻離竿尾的長度爲K,那麼另一頭竿尾的長度爲L-K。用窮竭搜索就可以找到最短和最長的時間。PS:之前用c++的cin和cout輸入輸出流,一直都是TLE……- -找了半天問題。。

#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
using namespace std;
#define min(a,b) (a)<(b)? a:b
#define max(a,b) (a)>(b)? a:b
int n,L;
int a[1000000];
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        int MIN=0;
        int MAX=0;
        scanf("%d%d",&L,&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
            MIN=max(MIN,min(a[i],L-a[i]));
            MAX=max(MAX,max(a[i],L-a[i]));
        }
        printf("%d %d\n",MIN,MAX);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章