Black Technology - tree cross twice \ (dfs \) turn a \ (dfs \) !
Weight is well known that the tree is usually split chain to \ (dfs \) twice, like this:
int Fa[N],dep[N],Sz[N],son[N];
void dfs1(int x,int pre){
Fa[x]=pre,dep[x]=dep[pre]+1;
Sz[x]=1;
erep(i,G,x){
int y=G.to[i];
if(y==pre)continue;
dfs(y,x);
Sz[x]+=Sz[y];
(Sz[y]>Sz[son[x]])&&(son[x]=y);
}
}
int L[N],R[N],Id,top[N];
void dfs2(int x,int tp){
top[x]=tp;
if(son[x])dfs2(son[x],tp);
erep(i,G,x){
int y=G.to[i];
if(y==Fa[x]||y==son[x])continue;
dfs2(y,y);
}
}
But in some \ (n \) is relatively large and theOften cancer card titleWe used twice if \ (dfs \) is likely to occur \ (tle \) situations.
In this case, the nature of the case, if we can not optimize algorithms we often need card.
How card it? Use \ (dfs \) sequence:
code show as below:
int Fa[N],dep[N],Sz[N],son[N],L[N],R[N],Id[N],cnt,top[N];
void dfs1(int x,int pre){
Fa[x]=pre,dep[x]=dep[pre]+1;
Sz[x]=1,L[x]=++cnt,Id[cnt]=x;
erep(i,G,x){
int y=G.to[i];
if(y==pre)continue;
dfs(y,x);
Sz[x]+=Sz[y];
(Sz[y]>Sz[son[x]])&&(son[x]=y);
}
R[x]=cnt;
}
rep(i,1,n)top[Id[i]]=Id[i]==son[Fa[Id[i]]]?top[Fa[Id[i]]]:Id[i];
So we only used once \ (dfs \) to complete the pre-operating section of the tree.
Do not underestimate this a recursive, he \ (\ n) is large, you can soon probably \ (1 \) times.