P4387. 验证栈序列

考点

  • 模拟

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <bits/stdc++.h>
using namespace std;
const int LEN = 1e5 + 10;

void f()
{
int a[LEN], b[LEN];
stack<int> st;
int n;
cin >> n;
for (int i = 1; i <= n; ++i)
cin >> a[i];
for (int i = 1; i <= n; ++i)
cin >> b[i];
int i = 1, j = 1;
while (i <= n || j <= n)
{
while (!st.empty() && b[j] == st.top())
{
st.pop();
++j;
}
if (i > n && !st.empty())
break;
if (i <= n)
st.emplace(a[i++]);
}
if (st.empty())
cout << "Yes" << endl;
else
cout << "No" << endl;
}

int main()
{
int q;
cin >> q;
while (q--)
f();
return 0;
}

思路

想了很多骚思路都超时,直接模拟出栈情况就行.....

每个即将入栈的元素,有两种选择:

  1. 留在栈里
  2. 不入栈,直接输出

所以在编程的时候,每次只能进行一次操作:

  1. 要么将入栈序列的一个元素压入栈

  2. 要么写一个循环,只要当前出栈序列的元素等于栈顶

    那么栈就弹出一个元素,出栈序列选择下一个元素