提交时间:2020-11-16 15:51:42

运行 ID: 1855

#include<bits/stdc++.h> using namespace std; const int maxn=1e6+5; inline int read(){ int x=0,f=1,ch=getchar(); while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} while(ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+ch-48;ch=getchar();} return x*f; } int n,h[maxn],e_cnt,fa[maxn],p[maxn],stk[maxn],stk_top,ans[maxn]; struct edge{int t,nxt;}e[maxn<<1]; void add_edge(int f,int t){ e[++e_cnt]=(edge){t,h[f]}; h[f]=e_cnt; } int get_lower(int l,int r,int k){ int mid=(r+l)/2,ans=0; while(l<=r){ mid=(r+l)/2; if(stk[mid]<=k){ans=mid;r=mid-1;} else l=mid+1; } return ans; } void print_stk(){ cout<<"stk: "<<stk_top<<endl; for(int i=1;i<=stk_top;i++)cout<<stk[i]<<" ";cout<<endl; cout<<endl; } void dfs(int x){ ans[x]=stk_top; for(int i=h[x];i;i=e[i].nxt){ int k=get_lower(1,stk_top,p[e[i].t]); if(!k)k=stk_top+1; int t=stk[k],ctop=stk_top; stk[k]=p[e[i].t];stk_top=k; dfs(e[i].t); stk[k]=t;stk_top=ctop; } } int main(){ n=read(); for(int i=2;i<=n;i++)fa[i]=read(),add_edge(fa[i],i); for(int i=1;i<=n;i++)p[i]=read(); stk[++stk_top]=p[1]; dfs(1); for(int i=1;i<=n;i++)printf("%d ",ans[i]);printf("\n"); return 0; }