【洛谷题解/深基15.习9 P4387验证栈序列

题目概况

链接: https://www.luogu.com.cn/problem/P4387
难度: 普及/提高-

题目分析

想一下,我们验证给定的栈序列的出入栈顺序是否合法时,是怎么做的?
是不是先入一个元素,如果栈顶元素按照顺序可以出,就按照出栈顺序,依次出栈.如果到最后这个栈出不完了(或者说非空),那么就是非法的出入栈顺序.
所以我们按照这个逻辑模拟一遍就行了.
涉及知识点为栈与模拟.

代码

#include 
#include 
#include 

using namespace std;
const int N = 1e5 + 5;

int q, pushed[N], poped[N];

int main() {
	scanf("%d", &q);
	while (q--) {
		int n, sum = 1; 
		stack <int> s;
		
		scanf("%d", &n);
		for (int i = 1; i <= n; i++) scanf("%d", &pushed[i]);
		for (int i = 1; i <= n; i++) scanf("%d", &poped[i]);
		
		for (int i = 1; i <= n; i++) {
			s.push(pushed[i]); //入栈
			while (!s.empty() && s.top() == poped[sum]) {
				s.pop();
				sum++;
			} 
		}
		if (!s.empty()) printf("No\n");
		else printf("Yes\n");
	}
	return 0;
}

你可能感兴趣的:(洛谷题解,c语言,算法,开发语言)