1. 程式人生 > >【PAT】1051. Pop Sequence (25)【棧的使用】

【PAT】1051. 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.

翻譯:給你一個可以儲存最多M個數字的棧。往裡面以1,2,3,……的順序壓入N個數字,可以隨機丟擲。你需要說出給定的數字數列是否是可能的棧的丟擲數列。舉個例子,如果M是5而N是7,我們可以從棧得到 1, 2, 3, 4, 5, 6, 7,但是不能得到 3, 2, 1, 7, 5, 6, 4.。

INPUT FORMAT

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.

翻譯:每個輸入檔案包含一組測試資料。對於每組輸入資料,第一行包括3個數字(所有都不大於1000):M(棧的最大容量),N(推入數列的長度),和K(檢測的輸出佇列數)。接著K行,每行包括一個N個數字的丟擲佇列。一行內所有數字之間用空格隔開。

OUTPUT FORMAT

For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.

翻譯:對於每組丟擲數列,輸出一行“YES”如果確實是棧可能的輸出數列,否則輸出“NO”。

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也算錯誤。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<stack>
#include<algorithm>
#define INF 99999999
using namespace std;
int M,N,K;
int main(){
    scanf("%d%d%d",&M,&N,&K);
    for(int i=0;i<K;i++){
        int a;
        bool v[1010];
        memset(v,0,sizeof(v));
        stack<int> s;
        int flag=0;
        s.push(0);
        for(int j=0;j<N;j++){
            scanf("%d",&a);
            if(flag==0){
                if(a>s.top()){
                    for(int k=s.top()+1;k<=a;k++)if(!v[k])s.push(k);
                    if(s.size()>M+1)flag=1;
                }
                if(a==s.top())v[a]=true,s.pop();
                if(a<s.top())flag=1;
            }
        }
        if(flag==0)printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}