思路:将整棵树划分成 n 个子树
坑点:maxn 最小取 49 (我也不知道为啥,题目明明是 n<30)
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn = 50; // 试了几次,发现最小取 49,可以过
int a[maxn],b[maxn];
struct node{
int l,r;
}tree[maxn];
int build(int x1,int y1,int x2,int y2){
if(x1>y1) return 0;
int k=x1;
while(a[k]!=b[x2]) k++;
tree[b[x2]].l = build(x1,k-1,x2+1,x2+k-x1);
tree[b[x2]].r = build(k+1,y1,x2+1+k-x1,y2);
return b[x2];
}
void print(int o){
int k=0;
queue<int> q;
q.push(o);
while(q.empty()==0){
int x=q.front();
if(k==0){
cout << x;
k=1;
}
else cout << ' ' << x;
q.pop();
if(tree[x].r!=0) q.push(tree[x].r);
if(tree[x].l!=0) q.push(tree[x].l);
}
cout << endl;
return;
}
int main()
{
int n;
cin >> n;
for(int i=0; i<n; i++)
cin >> a[i];
for(int i=0; i<n; i++)
cin >> b[i];
int o=build(0,n-1,0,n-1);
print(o);
return 0;
}