Rails UVA - 514(栈)

题目链接:https://vjudge.net/problem/UVA-514

题目大意:右边的火车经过中间的收费站到左边,右边火车进站的秩序是1~n   判断是否能以题中是所给的次序通过

思路:很明显的先进后出  显然是栈 ,这是第一道栈的题目,算是入了个门吧 ,会了栈就很简单了,不细讲,看代码:

#include<iostream>
#include<stack>
using namespace std;
const int maxn=1000+5;
int target[maxn];
int main()
{
    int n;
    while(cin>>n)
    {
        if(n==0) break;

        while(true)
        {

            stack<int>s;
            int flag=1;
            cin>>target[1];
            if(target[1]==0) break;
            for(int i=2;i<=n;i++) cin>>target[i];
            //1`n依次进站
            int A=1,B=1;//A是当前入站的车号 B是目标序列的下标
            while(B<=n)
            {
                if(A==target[B])//入站的等于出站的  直接出去
                {
                    A++;
                    B++;
                }
                else if(!s.empty()&&(s.top()==target[B]))//栈顶元素等于序列中的元素
                {
                    s.pop();
                    B++;
                }
                else if(A<=n) s.push(A++);
                else
                {
                    flag=0;
                    break;
                }
            }
            if(flag) cout<<"Yes"<<endl;
            else cout<<"No"<<endl;
        }
        cout<<endl;

    }
    stack<int>s;

}

猜你喜欢

转载自www.cnblogs.com/caijiaming/p/10338269.html