前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >02-线性结构4 Pop Sequence (25分)

02-线性结构4 Pop Sequence (25分)

作者头像
AI那点小事
发布2020-04-20 16:34:36
3840
发布2020-04-20 16:34:36
举报
文章被收录于专栏:AI那点小事

Given a stack which can keep MM numbers at most. Push NN numbers in the order of 1, 2, 3, …, NN 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 MM is 5 and NN 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): MM (the maximum capacity of the stack), NN (the length of push sequence), and KK (the number of pop sequences to be checked). Then KK lines follow, each contains a pop sequence of NN 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


AC代码:

代码语言:javascript
复制
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

int M;  //栈的最大容量 
int N;  //测试数据的长度 
int K;  //测试数据的组数 

/*
    这题是模拟给定序列出栈过程
    思路如下:
        当我们遇见输出x时,则要考虑的是x前的元素,即小于等于x的元素都先push栈,才会有pop x;
        1。栈为空时,判断需要填入的数 是否小于 栈的容量(即M)
        2。若后一个数比前一个数大,又要push其之前的数 再判断 
        3。若后一个数比前一个数小,则要判断栈顶元素是否与其相等
*/

bool Check_Seq(vector<int> &v)
{
    int i = 0;
    int num = 1;
    int cap = M+1;
    stack<int> sta;
    sta.push(0);
    while(i < N ){
        while(sta.size() < cap && v[i] > sta.top()){
            sta.push(num++); 
        }
        if ( v[i++] == sta.top()){
            sta.pop();
        }else{
            return false;
        }
    } 
    return true;
 } 

int main()
{
    cin>>M>>N>>K;
    vector<int> seq;

    for (int i = 0 ; i < K ; i++){
        for ( int j = 0 ; j < N ; j++){
            int tmp;
            cin>>tmp;
            seq.push_back(tmp);
        }
        if(Check_Seq(seq)){
            cout<<"YES"<<endl;
        }else{
            cout<<"NO"<<endl;
        }
        seq.clear();
    }

    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档