PAT-A-1051 Pop Sequence 【栈】

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.

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的栈,问你能否把1,2,3,4…N的序列调整成为样例输入中的序列形式。
有一点要注意,就是样例的第五组:1 7 6 5 4 3 2 。
1可以先出,23456入栈之后,7不能入栈了,所以是不行的
PAT-A-1051 Pop Sequence 【栈】_第1张图片

想法一:通栈的思想利用数组和一个指针变量来做

#include<bits/stdc++.h>
using namespace std;

int main()
{
    int i,j,n,m,k,t,a[1200],top,b[1200];//a存放输入的排列,top指向栈顶,b为栈
    while(~scanf("%d%d%d",&n,&m,&k))
    {
        while(k--)//数据组数
        {
            for(i=0;i<m;i++) scanf("%d",&a[i]);
            top=0,j=0,i=1;
            //i代表自然序列中考虑的值
            while(j<m)
            {
                if(i==a[j]&&top<n)//i和a[j]相等且栈有容量
                {
                    i++;
                    j++;
                }
                else if(top>0&&b[top]==a[j])//栈顶元素相同
                {
                    j++;
                    top--;
                }
                else if(top<n-1&&i<=m)//入栈缓存
                {
                    b[++top]=i;
                    i++;
                }
                else break;//其他情况一律跳出
            }
            //中途退出,不能完成
            if(j<m) printf("NO\n");
            else printf("YES\n");
        }
    }
    return 0;
}

想法二:利用C++中的stl自带的stack来做

#include<bits/stdc++.h>
using namespace std;
const int N=1024;
stack<int>st;
int a[N],n,m,k;

int check()
{
    while(!st.empty()) st.pop();
    int p=1,t;
    for(int i=0;i<n;i++)
    {
        while(p<=a[i])
        {
            st.push(p);
            p++;
            if(st.size()>m) return 0;
        }
        t=st.top();
        if(t!=a[i]) return 0;
        st.pop();
    }

    return 1;
}

int main()
{
    scanf("%d%d%d",&m,&n,&k);
    for(int _=0;_<k;_++)
    {
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        if(check()) puts("YES");
        else puts("NO");
    }
    return 0;
}

提交结果

第一种想法

第二种想法
PAT-A-1051 Pop Sequence 【栈】_第2张图片

你可能感兴趣的:(PAT-A-1051 Pop Sequence 【栈】)