1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| #include<bits/stdc++.h> using namespace std; const int N=1e6+10; int T,n,dfn[N],Time,last[N],f[N],eto[N]; vector<int>e[N],e2[N];
void dfs(int now,int fa) { dfn[now]=++Time; for(int to:e[now]) if(to!=fa)dfs(to,now); last[now]=Time; return; } bool find(int x,int l,int r) { if(l>r)return 0; if(e2[x].back()<l)return 0; if(e2[x][0]>r)return 0; int pos=0; int L=0,rr=e2[x].size()-1,mid; while(L<=rr) { mid=(L+rr)>>1; if(e2[x][mid]>=l)pos=mid,rr=mid-1; else L=mid+1; } return e2[x][pos]<=r; } void dfs2(int now,int fa) { f[now]=1; for(int to:e[now]) if(to!=fa) { dfs2(to,now); f[now]&=f[to]; eto[to]=find(now,dfn[to],last[to]); f[now]&=eto[to]; } return; } int ans=-1; void dfs3(int now,int fa) {
if(f[now]) { ans=now; return; } vector<int>g; g.clear(); g.resize(e[now].size()); int l=e[now].size(); for(int i=0;i<l;i++) if(e[now][i]!=fa)g[i]=f[e[now][i]]&eto[e[now][i]]; else g[i]=1; for(int i=l-2;i>=0;i--) g[i]&=g[i+1]; int fg=1; for(int i=0;i<l;i++) { int to=e[now][i]; if(to!=fa) { if(fg&&(i<l-1?g[i+1]:1)&&(find(to,1,dfn[to]-1)||find(to,last[to]+1,n))) dfs3(to,now); fg&=eto[to]&f[to]; } } } int main() { cin>>T; while(T--) { cin>>n; for(int i=1;i<=n;i++)e2[i].clear(),e[i].clear(); for(int i=2,p;i<=n;i++) { cin>>p; e2[p].push_back(i); e2[i].push_back(p); } for(int i=2,p;i<=n;i++) { cin>>p; e[p].push_back(i); e[i].push_back(p); } Time=0; dfs(1,0); for(int i=1;i<=n;i++) { for(int j=0;j<e2[i].size();j++)e2[i][j]=dfn[e2[i][j]]; sort(e2[i].begin(),e2[i].end()); } dfs2(1,0); ans=-1; dfs3(1,0); cout<<ans<<'\n'; } flushout(); return 0; }
|