栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

出栈序列(Pop Sequence)详解

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

出栈序列(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.

输入规范说明

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.

输出规范说明

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

输入样例

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

输出样例

YES
NO
NO
YES
NO

算法思想图解

我们以出栈序列元素为研究对象,一个一个判断之。先看出栈序列中第一个元素,第一个元素出栈,意味着小于它的整数曾经都已经入栈 ,也就是说出栈序列中下一个已出栈元素其值必然不小于栈顶元素(小于的都还在栈里面,不可能出栈了)所以不满足这个条件的出栈序列排除之;下一个已出栈元素其值大于栈顶元素,就让小于它的整数继续入栈,如果超出栈的容量大小,也排除之。如果所有元素都满足我们的要求,那么这个出栈序列就是正确的。

#include
using namespace std;

int main()
{
    int M,N,K;
    cin>>M>>N>>K;
    int input;
    int j;
    int arr[1000];//用来存放随机出栈序列
    //有K个需要判断的随机出栈序列
    for(int i=0;i>input;
            arr[i]=input;
        }
        //初始化一个堆栈
        int stack[1000];
        int top=-1;
        //栈中第一个元素设置为1
        int num=1;
        stack[++top]=num;
        //用来检查出栈序列中的每一个元素
        for(j=0;jstack[top])
            {
                stack[++top]=++num;
            }
            if(top>=M)
                break;
            if(stack[top]==arr[j])
                    top--;//注意此时num的值是没有减少的,意味着小于下次入栈元素的整数不包括已经出栈的数
            //应对出栈序列是栈底的情况
            if(top<0)
                stack[++top]=++num;
        }
        if(j==N)
            cout<<"YES"<
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/629097.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号