思路:
递归
比较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+5; 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+1,r,ll+1,rr,a[l]); } else{ par[a[l]]=par[b[ll]]=pa; sum[pa]+=2; int len1=posa[b[ll]]-l; int len2=posb[a[l]]-ll; dfs(l+1,l+len1-1,posb[a[l]]+1,posb[a[l]]+len1-1,a[l]); dfs(posa[b[ll]]+1,posa[b[ll]]+len2-1,ll+1,ll+len2-1,b[ll]); while(sum[pa]==2)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=1;i<=n;i++)scanf("%d",&a[i]),posa[a[i]]=i; for(int i=1;i<=n;i++)scanf("%d",&b[i]),posb[b[i]]=i; mem(sum,0); dfs(1,n,1,n,0); for(int i=1;i<=n;i++)printf("%d%c",par[i]," "[i==n]); } return 0; }