给出两个序列 pushed 和 poped 两个序列,其取值从 1 到 $n(n\le100000)$。已知入栈序列是 pushed,如果出栈序列有可能是 poped,则输出 Yes,否则输出 No。为了防止骗分,每个测试点有多组数据。
第一行一个整数 $q$,询问次数。
接下来 $q$ 个询问,对于每个询问:
第一行一个整数 $n$ 表示序列长度;
第二行 $n$ 个整数表示入栈序列;
第三行 $n$ 个整数表示出栈序列;
对于每个询问输出答案。
2 5 1 2 3 4 5 5 4 3 2 1 4 1 2 3 4 2 4 1 3
Yes No
#include <bits/stdc++.h> using namespace std; stack<int> s; int q, n, t, a[100010], b[100010]; bool flg = true; int main() { cin >> q; for (int i = 0; i < q; i++) { int sum = 0; cin >> n; for (int j = 0; j < n; j++) scanf("%d", &a[j]); for (int j = 0; j < n; j++) scanf("%d", &b[j]); for (int j = 0; j < n; j++) { s.push(a[j]); while ((s.top()) == b[sum]) { s.pop(); sum++; if (s.empty()) break; } } if (s.empty()) cout << "Yes" << endl; else cout << "No" << endl; while (!s.empty()) s.pop(); } return 0; }