Rails

 列车问题,十分经典的对栈运用的题目

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<algorithm>
using namespace std;
stack<int> s;
int main()
{
    int n;
    int target[2200];
    while(~scanf("%d",&n))
    {
        if(n == 0)
            return 0;
        while(~scanf("%d",&target[1]))
        {
            if(target[1] == 0)
            {
                cout<<endl;
                break;
            }
            for(int i = 2; i <= n; i++)
                scanf("%d",&target[i]);
            int a,b;
            a = b = 1;
            bool mark = true;
            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);
                    a++;
                }
                else
                {
                    mark = false;
                    break;
                }
            }
            if(mark == true) printf("Yes
");
            else printf("No
");
        }
    }
}

  

原文地址:https://www.cnblogs.com/zzzying/p/7202245.html