题意

  1. 输入序列长度n
  2. 在栈中依次输入1、2、3 ... n
  3. 给你一组出栈方式,判断是否合法

Code

Cpp

#include <bits/stdc++.h>

using namespace std;

const int N = 1010;

int n;
int a[N], idx;
string str;
stack<int> st;

int main()
{
    while (cin >> n && n)
    {
        getchar();
        while (getline(cin, str) && str != "0")
        {
            idx = 0;
            string token;
            istringstream iss(str);
            while (getline(iss, token, ' ')) // 实现split
            {
                a[ ++ idx] = stoi(token);
            }
            
            for (int i = 1, j = 1; i <= n; i ++ )
            {
                st.push(i);
                while (!st.empty() && j <= n && st.top() == a[j]) j ++, st.pop();
            }
            if (st.empty()) cout << "Yes\n";
            else cout << "No\n";
            
            while(!st.empty()) st.pop(); // 清空stack
        }
        cout << endl;
    }
}

Python

n = int(input())

while n:
    data = input()
    while data != '0':
        data = list(map(int, data.split()))
        i = 1
        j = 0
        st = []
        for item in data:
            st.append(i)
            i += 1
            while j < n and len(st) and st[len(st) - 1] == data[j]:
                st.pop()
                j += 1
        if len(st) > 0:
            print('No')
        else:
            print('Yes')
        data = input()
    print('')
            
    n = int(input())
    ```