P4387 【深基15.习9】验证栈序列

这是一个关于栈操作的问题,给定两个序列pushed(入栈顺序)和popped(出栈顺序),程序需要判断在栈操作下popped是否可能由pushed产生。文章提供了输入输出格式以及样例,并给出了一段C++代码实现验证过程。
摘要由CSDN通过智能技术生成

【深基15.习9】验证栈序列

题目描述

给出两个序列 pushed 和 poped 两个序列,其取值从 1 到 n ( n ≤ 100000 ) n(n\le100000) n(n100000)。已知入栈序列是 pushed,如果出栈序列有可能是 poped,则输出 Yes,否则输出 No。为了防止骗分,每个测试点有多组数据。

输入格式

第一行一个整数 q q q,询问次数。

接下来 q q q 个询问,对于每个询问:

第一行一个整数 n n n 表示序列长度;

第二行 n n n 个整数表示入栈序列;

第三行 n n n 个整数表示出栈序列;

输出格式

对于每个询问输出答案。

样例 #1

样例输入 #1

2
5
1 2 3 4 5
5 4 3 2 1
4
1 2 3 4
2 4 1 3

样例输出 #1

Yes
No
#include <bits/stdc++.h>
#define LL long long 
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 1e6;
int q;
stack<int> a;
stack<int> b;
int aa[N];
int bb[N];
int n;
int main(){
    cin >> q;
    while(q--){
        cin >> n;
        for(int i = 1;i <= n;i ++){
            cin >> aa[i];
        }
        for(int i = 1;i <= n;i ++){
            cin >> bb[i];
        }
        for(int i = n;i >= 1 ;i --){
            b.push(bb[i]);
        }

        for(int i = 1;i <= n;i ++){
            a.push(aa[i]);
            while(a.top() == b.top()){
                a.pop();
                b.pop();
                if(a.empty())
                    break;
            }
        }
        if(b.empty())
            cout << "Yes" << endl;
        else
            cout << "No" << endl;
        while(!a.empty()) a.pop();
        while(!b.empty()) b.pop();
    }
    system("pause");
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值