【紫书】Rails UVA - 514 栈

题意:判断出栈顺序是否合法

题解:两个指针,A指向入栈序列,B指向出栈。

  的分三种情况:if     1.A==B :直接入栈加出栈即可A++,B++

         else 2.和栈顶相同,直接出栈A==stack.top   A++,stack.pop

         else 3. 都不符合 压入栈stack.push(A)

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstring>
#include<queue>
#include<string.h>
#include<algorithm>
#include<stack>
using namespace std;
const int maxn = 1000+5;
int target[maxn];
stack<int> s;
int main() {
    int n;
    while (cin >> n) {
        if (n == 0)break;
        while (cin >> target[1])
        {
            if (target[1] == 0) break;
            for (int i = 2; i <= n; i++) {
                cin >> target[i];
            }
            int ok = 1;
            int A=1, B=1;
            while (B <= n) {
                if (A == target[B]) A++, B++;
                else if (!s.empty() && target[B] == s.top()) s.pop(), B++;
                else if (A <= n) s.push(A++);
                else { ok = 0; break; }
            }
            ok ? puts("Yes") : puts("No"); 
        }
        cout << endl;
    }
}

 

posted @ 2018-04-12 10:55  SuuTTT  阅读(143)  评论(0编辑  收藏  举报