对一个空栈进行 push 和 pop 操作各 n 次,使得 1-n 每个数都被 push 和 pop 一次,n 次 push 的数按照顺序形成排列 A,n 次 pop 的数按照顺序形成排列 B,此时称 A 和 B 互为“栈转化序列”。
Input
三行,第一行为一个整数 n(0<n≤100),第二行和第三行分别为 1-n 的两个排列 A, B。
Output
一行,如果 A 和 B 互为“栈转化序列”就输出 “True” ,否则输出 “False” 。
Sample
input
6
1 2 3 4 5 6
5 6 4 3 2 1
output
True
Note
样例中的操作顺序是:
push(1),push(2),push(3),push(4),
push(5),pop(5),
push(6),pop(6),
pop(4),pop(3),pop(2),pop(1)。
#include <iostream>
using namespace std;
int main(){
int n, A[100] = {0}, B[100] = {0};
cin >> n;
for(int i = 0; i < n; i++){
int temp;
cin >> temp;
A[temp] = i; //注意数组元素值为位置
}
for(int i = 0; i < n; i++){
cin >> B[i];
}
for(int i = 0; i < n - 1; i++){ //B数组外循环
int max = n - 1;
for(int j = i + 1; j < n; j++){
if(A[B[i]] > A[B[j]]){
if(A[B[j]] > max){
cout << "False" << endl;
return 0;
}
else{
max = A[B[j]];
}
}
}
}
cout << "True" << endl;
return 0;
}
浙公网安备 33010602011771号