思路:
递归
比较a序列和b序列中表示同一个子树的一段区间,不断递归
代码:
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pb push_back
#define mem(a,b) memset(a,b,sizeof(a)) const int N=1e5+;
int a[N],b[N],par[N],posa[N],posb[N],sum[N],n;
void dfs(int l,int r,int ll,int rr,int pa){
if(l>r||ll>rr||r>n||rr>n)return ;
if(a[l]==b[ll]){
par[a[l]]=pa;
sum[pa]++;
dfs(l+,r,ll+,rr,a[l]);
}
else{
par[a[l]]=par[b[ll]]=pa;
sum[pa]+=;
int len1=posa[b[ll]]-l;
int len2=posb[a[l]]-ll;
dfs(l+,l+len1-,posb[a[l]]+,posb[a[l]]+len1-,a[l]);
dfs(posa[b[ll]]+,posa[b[ll]]+len2-,ll+,ll+len2-,b[ll]);
while(sum[pa]==)pa=par[pa];
dfs(l+len1+len2,r,ll+len1+len2,rr,pa);
}
}
int main(){
int T;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
for(int i=;i<=n;i++)scanf("%d",&a[i]),posa[a[i]]=i;
for(int i=;i<=n;i++)scanf("%d",&b[i]),posb[b[i]]=i;
mem(sum,);
dfs(,n,,n,);
for(int i=;i<=n;i++)printf("%d%c",par[i]," \n"[i==n]);
}
return ;
}