- C++
P4387 【深基15.习9】验证栈序列【题解】
- 2024-1-29 21:10:18 @
【深基15.习9】验证栈序列
题目描述
给出两个序列 pushed 和 poped 两个序列,其取值从 1 到 。已知入栈序列是 pushed,如果出栈序列有可能是 poped,则输出 Yes
,否则输出 No
。为了防止骗分,每个测试点有多组数据。
输入格式
第一行一个整数 ,询问次数。
接下来 个询问,对于每个询问:
第一行一个整数 表示序列长度;
第二行 个整数表示入栈序列;
第三行 个整数表示出栈序列;
输出格式
对于每个询问输出答案。
样例 #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>
using namespace std;
const int N = 1e6+10;
int q,n,stk1[N],stk2[N],top1,top2;
int main(){
stk1[0]=1;
cin>>q;
// cout<<"q:"<<q<<"n:"<<n<<endl;
for(int i=0;i<q;i++){
cin>>n;
for(int j=1;j<=n;j++) cin>>stk1[j];
for(int j=n;j>=1;j--) cin>>stk2[j];
top1=1;
top2=n;
for(int j=1;j<=n;j++){
while(stk1[top1]==stk2[top2]){
// cout<<stk1[top1]<<" "<<stk2[top2]<<endl;
top1--;top2--;
}
if(j!=n){
stk1[++top1]=stk1[j+1];
}
}
if(top1==0&&top2==0){
cout<<"YES"<<endl;
}else{
cout<<"NO"<<endl;
}
}
return 0;
}
0 条评论
目前还没有评论...