PAT甲级真题 1051 Pop Sequence (25分) C++实现(检查递减序列是否合法)

本文探讨了如何判断一个给定的数列是否能通过一个有限容量的栈进行压栈和弹栈操作得到。输入包括栈的最大容量、压栈序列长度及待验证的弹栈序列数量。文章提供了详细的解题思路与C++代码实现。

题目

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

思路

某个元素a[i]后面,比a[i]小的值构成的连续序列需满足:

  1. 递减
  2. 长度不超过栈高

从第一个元素开始,不断找上述连续序列,若其中有不符合要求的,则输出“NO”;若将序列正常遍历结束,则输出“YES”。

柳神用了模拟栈的方法,更直观一点。

代码

#include <iostream>
#include <vector>
using namespace std;

int main(){
    int m, n, k;
    cin >> m >> n >> k;
    vector<int> a(n); 
    for (int i=0; i<k; i++){ 
        for (int j=0; j<n; j++){ 
            cin >> a[j];
        }
        bool ret = true;
        //l到r是降序序列
        int l = 0;
        while (l<n){
	        //找比a[l]小的元素构成的序列
            int r = l+1;
            while (r<n && a[r]<a[l]){
            	//若非递减,则不合法
                if (a[r]>a[r-1]){
                    ret = false;
                    break;
                }
                r++;
            }
            //若长度大于栈高,则不合法
            if (r-l > m){
                ret = false;
                break;
            }
            l = r;
        }
        if (ret){
            cout << "YES" << endl;
        }
        else{
            cout << "NO" << endl;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值