Poj-1363-Rails-棧

題面:
There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.
大意:
給出若干個長度爲n的序列,問該序列能否由序列123……n依次入棧並出棧得到
AC代碼:

int coach[1001];//車廂
stack<int> s;//棧
int main()
{
    int n;
    while(scanf("%d",&n) && n)//簡潔的判斷方法,學習了
    {
        while(scanf("%d",&coach[1]) && coach[1])//同上
        {
            for(int i = 2; i <= n; ++i)//輸入剩餘車廂的編號
                scanf("%d",&coach[i]);
            int j = 1;//指針
            for(int i = 1; i <= n; ++i)//模擬序列123......n入棧的過程
            {
                s.push(i);//入棧
                //首先要判斷非空,才能訪問棧頂元素
                //這裏用到循環是因爲可能會執行多次
                while(!s.empty() && s.top() == coach[j])//棧頂元素是否等於coach的第j個元素
                {
                    s.pop();//是的話就出棧
                    j++;//指針後移
                }
            }
            if(j == n + 1)//j是否被累加了n次,是的話就代表這n個數全部出棧,此時棧爲空
                printf("Yes\n");
            else
                printf("No\n");
            //爲什麼需要重置?
            //明明會被覆蓋!
            memset(coach,0,sizeof(coach));// ?????寫了這句就AC了
        }
        cout << endl;
    }
    return 0;
}

解決方法:
①while(~scanf(“%d%d”,&m,&n))等同於while(scanf(“%d%d”,&m,&n) != EOF)
因爲EOF爲-1,-1十六進制補碼錶示爲0xffffffff,f是二進制的1111,所以按位取反後就會變成0
②忘記s.pop()會導致死循環
③一個方向不行就換一個方向。說不定那個方向易於實現

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