UVA514铁轨

同样是栈的运用,紫书的例题。

1.在中转站c中,车厢符合后进先出的原则,因此是一个栈。

2.以给出的特定的顺序为标准吧,以下几种情况

若B中的数与A相同则B++,查看B中下一个数

若C中的栈顶元素与B中的数相同,则栈顶元素出栈,B++,查看B中下一个数

A不超过n时,将A入栈

以上都不满足时则说明不能以特定顺序进入B方向的铁轨并出车站

#include <iostream>  
#include <cstring>  
#include <cstdio>  
#include <cmath>  
#include <stack>  
using namespace std;  
int main()  
{  
    int n,a[1010];  
    while(cin>>n&&n)  
    {  
        stack<int> s;  
        memset(a,0,sizeof(a));  
        while(cin>>a[1])  
        {  
            if(a[1]==0)  
            {  
                cout<<endl;  
                break;  
            }  
            for(int i=2; i<=n; i++)  
                cin>>a[i];  
            int A = 1,B = 1;  
            bool sign = true;  
            while(B<=n)  
            {  
                if(A==a[B])  
                {  
                    A++;  
                    B++;  
                }  
                else if(!s.empty()&&s.top()==a[B])  
                {  
                    s.pop();  
                    B++;  
                }  
                else if(A<=n)  
                    s.push(A++);  
                else  
                {  
                    sign = false;  
                    break;  
                }  
            }  
            printf("%s\n",sign ? "Yes" : "No");  
        }  
    }  
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/sgsyacm/article/details/79479064
今日推荐