1. 程式人生 > 實用技巧 >PAT1051 Pop Sequence (25分) 模擬入棧

PAT1051 Pop Sequence (25分) 模擬入棧

題目

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:
Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:
For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.

Sample Input:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2

Sample Output:

YES
NO
NO
YES
NO

解析

題目:

有一個棧,大小為M

,有N個數字,數字1~N只能按順序依次入棧。給出K個出棧序列,判斷該序列是否是可以實現的出棧序列。

思路:

  • 入棧順序是確定的(1-N依次入棧),我們只需要模擬這個過程。
  • 先把輸入的序列接收進陣列seq[],設index= 1,表示當前比較的是序列哪個元素,然後按順序1~n把數字進棧,每進入一個數字,判斷有沒有超過棧容量m,超過了就break
  • 如果沒超過,看看當前序列元素seq[index]是否與棧頂元素s.top()相等:while相等就一直彈出棧s.pop()index++,相當於當前序列元素匹配成功,繼續處理下一個;不相等就繼續按順序把數字壓入棧。若能完美模擬,最終棧應該是空的,說明這個序列是可能的,輸出YES

程式碼

#include <iostream>
#include <stack>
#include <vector>
using namespace std;
int main() {
    // 棧容量m,序列長度n,k個序列
    int m, n, k;
    cin >> m >> n >> k;
    while (k -- > 0) {
        vector<int> seq(n + 1);
        stack<int> s;
        // 序列哪個位置元素
        int index = 1;
        // 輸入這個序列
        for (int j = 1; j <= n; ++j) cin >> seq[j];
        // 模擬入棧過程(只能從1到n入棧)
        for (int j = 1; j <= n; ++j) {
            s.push(j);
            // 棧中元素不能超過m個
            if (s.size() > m) break;
            // 如果當前棧頂元素和當前序列元素相等
            while (!s.empty() && s.top() == seq[index]) {
                // 出棧,相當於成功匹配這個元素
                s.pop();
                // 處理序列下一個元素
                index++;
            }
        }
        // 如果最終棧空,說明這個序列可以是正確的出棧序列
        if (s.empty()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}