PAT Advanced 1051 Pop Sequence

1051 Pop Sequence

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的棧,從棧底到頂的依次push爲1- n, 給定k次枚舉,判斷是否能按照輸入的要求通過依次pop,輸出得到剛剛輸入的值, 如果能輸出YES, 否則NO, 並且stack中最大容量爲m, 如果超過m的話, 也算NO

  • 思路過程:
    每次都將1-n的數push進stack中, 之後棧頂和輸入的a[idx]比較,如果相同的話,idx指向a中的下一個位置, stack要pop出棧頂元素,一直檢測此條件,相同並且棧不爲空就一直pop, 不滿足條件時就繼續push。最終stack中存在元素或者中間的過程stack存儲的元素個數超過m,輸出no, 否者爲yes。 此過程枚舉k次即可。

解題代碼

c模擬stack很簡潔, c編譯改一下頭文件, 看了很多其他人寫的c版本貌似沒看到 比我這18行精簡的了吧:

#include <cstdio>
int m, n, k, a[1010];
int main(){
    scanf("%d %d %d", &m, &n, &k);
    while (k --){
        int st[1010], tt = 1, idx = 1, flag = 0;
        for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
        for (int i = 1; i <= n; i++){
            st[tt] = i;
            if (tt > m) flag = 1;
            while (tt > 0 && st[tt] == a[idx]) tt --, idx ++;
            tt ++;
        }
        if (tt > 1 || flag) puts("NO");
        else puts("YES");
    }
    return 0;
}

使用STL:

#include <iostream>
#include <stack>
using namespace std;
int m, n, k, a[1110];
int main(){
    scanf("%d %d %d", &m, &n, &k);
    while (k --){
        stack<int> st;
        for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
        int idx = 1;
        bool flag = false;
        for (int i = 1; i <= n; i++){
            st.push(i);
            if (st.size() > m) flag = true;
            while (!st.empty() && st.top() == a[idx])
                st.pop(),idx ++;
        }
        if (st.size() || flag) puts("NO");
        else puts("YES");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章