NOJ [1289] Will TT Get Snacks?

  • 问题描述
  • Mr. Cai and TT were playing in a beautiful sandy beach, and TT discovered a tree branch with many ant walking on it.

    TT noticed that when one ant meet another, they would turn back and keep on walking, when an ant walk straight to the side of the branch and there is no block on it's road(if exist, this ant will meet another and turn back,then it can't walk out the branch), it will walk out the branch and disappear. Mr.Cai also noticed this, he said:"TT, if you tell me how long will all the ants disappear and how long is the first ant walked out, I'll buy you many many snacks as praise."


  • 输入
  • There are many cases. First there are two integers len and n, means the length of the branch and the number of the ant.then followed n lines, the ith line includes the ith ant's position to the left side and it's position. Suppose all the ants walk 1m/s, and no time will waste in every meet or turn back.
  • 输出
  • For each case, output the maximun time these ants spent and the mininum time the first ant walked out.


    我的第一感觉是用O(n^2)的做法,显然会超时,所以要来找找有什么规律没,先考虑最大时间:

    NOJ [1289] Will TT Get Snacks?_第1张图片
    我们设A位置是5,B位置为15,长为20 ,且相向而行,则,A掉落时间:20,B掉落时间:15,max_time=15;
    现在,我们想象下,如果相遇时,蚂蚁们不是掉头而行,而是穿过去,则 A:15,B为15,max_time=15;
    现在,我们来泛化这个情况
    设A为X1,B为X2,则按题意,A走过的路为(X1+X2)/2 -X1+(X1+X2)/2=X2;
    B走过的路为(X2-  (X1+X2)/2)+len- (X1+X2)/2=len-X1;
    max_time=max(len-X1,X2);
    如果是穿过去的话,A:len-X1
    B:X2;
    max_time= max(len-X1,X2);
    实际两种是一样的

    同理,最小值也一样,所以,只要找到一只按自己方向走到底的蚂蚁,他的时间最长或最短就可以了
     

    #include<stdio.h>
    #include<string.h>

    struct ANT
    {
    int pos;
    char dir;
    }ant[2000];
    int main()
    {
    int n,len;
    while(~scanf("%d%d",&len,&n))
    {
    int i;
    int max=-1,min=0x3f3f3f3f;
    for(i=0;i<n;i++)
    {
    int length;
    scanf("%d %c%*c",&ant[i].pos,&ant[i].dir);
    if(ant[i].dir=='l')
    length=ant[i].pos;
    else
    length=len-ant[i].pos;
    max=(max>length?max:length);
    min=(min<length?min:length);
    }
    printf("max = %d\n",max );
    printf("min = %d\n", min);
    }
    return 0;
    }


你可能感兴趣的:(NOJ [1289] Will TT Get Snacks?)