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

【深基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;
}

猜你喜欢

转载自blog.csdn.net/Recursions/article/details/128550332