BNUOJ 26579 Andrew the Ant

LINK:Andrew the Antphp

題意:給一根長度爲L的木頭,上面有A只螞蟻【每隻螞蟻給出了初始行走的方向,向左或向右】。當兩隻螞蟻相碰時,兩隻螞蟻就朝相反的方向行走~╮(╯▽╰)╭問的是:最後掉下來的螞蟻用時多少,而且它的初始位置是哪裏?【如有兩隻,就先輸出初始位置小的那隻】~ios

這道題跟白書裏的那道題十分的像,不過白書問的是:給出時間T,問最後每隻螞蟻的位置是什麼~數組

題目的關鍵是:spa

      1.當兩隻螞蟻相碰的時候,其實就好像是兩隻螞蟻穿過了~那麼,每輸入一隻螞蟻,那麼必定存在對應的一隻螞蟻【也多是自身】符合:若它要掉下來,那麼它走的路程就是——若向右,X=L-P;若向左,X=P【X爲要走的路程,P爲輸入的那隻螞蟻的初始座標,L爲木頭長度】。因爲速度是一格每秒,故最後的那隻螞蟻掉下來的螞蟻用時T爲全部X中最大的~一樣,因爲把螞蟻相碰當成對穿而過,就沒辦法肯定終態的螞蟻是始態的那隻螞蟻了。換句話說:咱們剩下就是搞清楚終態的螞蟻對應的是那隻始態的螞蟻~code

      2.其次,咱們能夠注意到螞蟻的相對位置是始終不變的,所以把全部目標位置從小到大排好序,則從左到右的每一個位置對應始態的從左到右的每隻螞蟻。因爲原題不必定按從左到右的順序輸入,還須要預處理計算出輸入中的第i只螞蟻的順序號order[i]。blog

代碼以下:get

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 
 7 #define Max 100111
 8 
 9 struct Ant {
10   int id;     //輸入順序
11   int p;      //輸入位置
12   int d;      //輸入螞蟻的方向,-1爲向左,1爲向右,0爲轉身中
13   bool operator < (const Ant& a) const {
14     return p>a.p;
15   }
16 }before[Max],after[Max];
17 
18 int order[Max];   //輸入的第i只螞蟻是終態中的左數第order[i]只~
19 
20 int main(){
21    int A,L;
22    while(~scanf("%d%d",&L,&A))
23    {
24        memset(before,0,sizeof(before));
25        memset(after,0,sizeof(after));
26        int i,j,MM=0;            //MM爲最後的螞蟻要掉下來的時間
27        for(i=0;i<A;i++)
28        {
29            int p,d;
30            char c;
31            scanf("%d %c",&p,&c);
32            d=(c=='L'?-1:1);
33            before[i]=(Ant){i,p,d};
34            after[i]=(Ant){0,0,d};     //終態的id是未知的
35            if(d==1)                   //計算出MM的值
36               MM=max(MM,L-p);
37            else
38               MM=max(MM,p-0);
39        }
40        for(i=0;i<A;i++)               //計算出通過MM時間後螞蟻的終態位置
41            after[i].p=(MM)*after[i].d+before[i].p;
42        //計算order數組
43        sort(before,before+A);         
44        for(i=0;i<A;i++)
45            order[before[i].id]=i;
46        //計算終態
47        sort(after,after+A);
48        for(i=0;i<A-1;i++)
49            if(after[i].p==after[i+1].p) after[i].d=after[i+1].d=0;
50         int k=0,x[3];                //x[]記錄的是最後兩隻螞蟻的始態,k爲最後掉下來的螞蟻數
51         memset(x,0,sizeof(x));
52        for(i=0;i<A;i++)
53        {
54            int a=order[i];
55            if(after[a].p==0 || after[a].p==L)
56                 x[k++]=before[a].p;
57        }
58        if(k==1) printf("The last ant will fall down in %d seconds - started at %d.\n",MM,x[0]);    
59        else
60        {
61            sort(x,x+2);
62            printf("The last ant will fall down in %d seconds - started at %d and %d.\n",MM,x[0],x[1]);
63        }
64    }
65    return 0;
66 }

//memory:4224KB    time:224msstring

相關文章
相關標籤/搜索