• 1051 Pop Sequence (25 分)简单模拟


    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
    思路:
      定义一个栈,进行出栈模拟。
        1、循环下标从1开始,因为进栈序列是从1,开始的。
        2、如果当前栈中元素个数大于最大值m则返回false
        3、如果栈顶元素和出栈序列第一个元素相同,则循环出栈,直到栈顶元素和出栈序列元素不匹配
        4、循环结束后,如果栈中还有元素则返回false
        5、否则,返回true
      详细请看代码
      
    #include<iostream>
    #include<vector>
    #include<algorithm>
    #include<queue>
    #include<string>
    #include<map>
    #include<set>
    #include<stack>
    using namespace std;
    
    bool check(int a[],int n,int m)
    {
        stack<int> st;
        int top=1;
        for(int i=1; i<n+1; i++)
        {
            st.push(i);
            if(st.size()>m)
                return false;
            //如果栈顶元素等于出栈序列第一个则出栈
            while(!st.empty()&&st.top()==a[top])
            {
                st.pop();
                top++;
            }
    
    
        }
        if(!st.empty())
            return false;
        return true;
    }
    
    
    int main()
    {
        int m,n,k;
        cin>>m>>n>>k;
        int a[n+1];
        for(int i=0; i<k; i++)
        {
            for(int j=1; j<n+1; j++)
                cin>>a[j];
            if(check(a,n,m))
                cout<<"YES"<<endl;
            else
                cout<<"NO"<<endl;
        }
        return 0;
    }
     
  • 相关阅读:
    深入方法(22)- 指针参数
    深入方法(21)- 开放数组参数
    深入方法(20)- 静态数组参数
    深入方法(19)- 过程中的方法
    深入方法(18)- 在接口区声明的方法都相当于提前声明了
    深入方法(17)- 提前声明
    WNMP(Windows + Nginx + PHP + MySQL) 安装
    Yii2框架 数据库常用操作
    Python 生成器与迭代器 yield 案例分析
    Python VS PHP 基础语法
  • 原文地址:https://www.cnblogs.com/zhanghaijie/p/10308562.html
Copyright © 2020-2023  润新知