给出两个序列 pushed 和 poped 两个序列,其取值从 1 到 n ( n ≤ 100000 ) n(n\le100000) n(n≤100000)。已知入栈序列是 pushed,如果出栈序列有可能是 poped,则输出 Yes
,否则输出 No
。为了防止骗分,每个测试点有多组数据。
第一行一个整数 q q q,询问次数。
接下来 q q q 个询问,对于每个询问:
第一行一个整数 n n n 表示序列长度;
第二行 n n n 个整数表示入栈序列;
第三行 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
using namespace std;
int q, n, idx;
stack<int> sta;//存下标
int a[100010], b[100010];
int main() {
cin >> q;
while (q--) {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
for (int i = 0; i < n; ++i) {
cin >> b[i];
}
for (int i = 0; i < n; ++i) {
//先入栈
sta.push(a[i]);
while (!sta.empty()) {
//可能有一连串要出栈(栈底的一连串都在等栈顶这个数的到来,来解除封印)
if (sta.top() == b[idx]) {
sta.pop();
idx++;
} else {
break;
}
}
}
if (!sta.empty() || idx != n) {
cout << "No" << endl;
} else {
cout << "Yes" << endl;
}
while (!sta.empty())
sta.pop();
idx = 0;
}
return 0;
}