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.

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

解题思路

本题考查的知识点是“栈push和pop的顺序是先进后出”,当栈顶元素和数列的当前的第一个元素相等时,直接将栈顶元素pop出;若不一致时,便按照自然数顺序放入元素,直到栈顶元素和当前第一个元素相等,若栈满时仍然没有找到和当前第一个元素相等的栈顶元素,那么该数列不通过栈获得。

易错点

  1. 注意在找到某一个元素是不可以获得的时候,不要直接跳出循环,而是要将该序列剩下的元素读完,再进行读下一串序列;
  2. 在每读入一串序列之前,需要先保证将栈清空,避免影响下一次判断。

代码

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

int main(){
    int M,N,K,i,j,k,F,temp;
    scanf("%d %d %d",&N,&M,&K);//N是栈的容量,M是输入元素的个数
    for (i=0;i<K;i++)//读入序列的数目
    {
        k = 0;
        F = 0;
        stack <int> s;//避免需要将栈清空,每一次都使用新的栈
        for (j=0;j<M;j++)
        {
            scanf("%d",&temp);
            if (F==0)
            {
                if (s.size()!=0 && temp==s.top())
                    s.pop();
                else
                {
                    while (s.size()<N && k<M && temp!=k){
                        s.push(++k);}

                    if (temp==s.top())//相等的没有入栈,也就不需要出栈
                        s.pop();
                    else//满了or所有元素放完了还是没有相等的
                        F = 1;
                }
            }
            
        }
        
        if (F==1)
            printf("NO\n");
        else
            printf("YES\n");
    }
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值