P4387 【深基15.习9】验证栈序列
栈 + 模拟
#include<iostream>
#include<stack>
#include<vector>
#include<cstdio>
using namespace std;
stack<int> stk;
int q;
int main(){
cin >> q;
while(q --){
int n;
cin >> n;
vector<int> pushed, poped;
for(int i = 0; i < n; i ++){
int x;
cin >> x;
pushed.push_back(x);
}
for(int i = 0; i < n; i ++){
int x;
cin >> x;
poped.push_back(x);
}
int i = 0, j = 0, flag = 0;
while(i < n && poped[j] != pushed[i]) stk.push(pushed[i ++]);
stk.push(pushed[i ++]);
while(j < n){
if(stk.size() && stk.top() == poped[j]) stk.pop(), j ++;
else{
while(i < n && poped[j] != pushed[i]) stk.push(pushed[i ++]);
if(i < n){
stk.push(pushed[i ++]);
continue;
}
flag = 1;
break;
}
}
while(stk.size()) stk.pop();
if(flag) puts("No");
else puts("Yes");
}
return 0;
}