P4387

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

题目描述

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

输入格式

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

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

第一行一个整数 \(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>
using namespace std;
const int N=1e5+5;
int q,n,a[N],b[N],st[N],pt;
signed main()
{
	ios::sync_with_stdio(false);
	cin>>q;
	while(q--)
	{
		cin>>n;
		for(int i=1;i<=n;i++)cin>>a[i];
		for(int i=1;i<=n;i++)cin>>b[i];
		pt=0;
		int flag=1,p1=1,p2=1;
		while(1)
		{
			pt++;
			st[pt]=a[p1];p1++;
			while(st[pt]==b[p2]&&pt>0)pt--,p2++;
			if(p1>n||p2>n)break;
		}
		if(p1==n+1&&p2==n+1)flag=1;
		else flag=0;
		cout<<(flag==1?"Yes\n":"No\n");
	}
	return 0;
}
posted @ 2023-04-02 10:14  N0zoM1z0  阅读(18)  评论(0编辑  收藏  举报