【題解】ZeroJudge c123: 00514 – Rails

【題目敘述】https://zerojudge.tw/ShowProblem?problemid=c123
Virtual Judge: https://vjudge.net/problem/UVA-514

#include <iostream>
#include <stack>

using namespace std;

int main() {
    int n;
    while (cin >> n && n){
        while (1){
            int a[n], point = 1;
            stack <int> stk;
            cin >> a[0];
            if (a[0] == 0) break;
            for (int i = 1; i < n; i++){
                cin >> a[i];
            }
            int i;
            for (i = 0; i < n; i++){
                if (!stk.empty() && stk.top() == a[i]){
                    stk.pop();
                }else if (a[i] >= point){
                    for (int j = point; j < a[i]; j++){
                        stk.push(j);
                    }
                    point = a[i] + 1;
                }else{
                    break;
                }
            }
            if (i == n){
                cout << "Yes" << endl;
            }else{
                cout << "No" << endl;
            }
        }
        cout << endl;
    }
    return 0;
}

Python 程式碼 (2019-08-06)

while True:
    n = int(input())
    if n == 0:
        break
    while True:
        nums = list(map(int, input().split()))
        if len(nums) == 1 and nums[0] == 0:
            break
        station = [0]
        a = []
        flag = True
        for i in range(1, n+1):
            a.append(i)
        for num in nums:
            while True:
                if num == station[-1]:
                    station.pop()
                    break
                elif num > station[-1]:
                    station.append(a.pop(0))
                elif num < station[-1]:
                    flag = False
                    break
            if not flag:
                print('No')
                break
        else:
            print('Yes')
分享本文 Share with friends