In a number of topics will encounter such a problem: undirected connectivity Graph G has n points, n-1 bar edge. Points are numbered from 1 to n sequentially .... is obviously a tree structure, but do not know the specific parent-child relationship, at this time need to transform a tree without root tree into a root tree, specifically explained as follows:
1. Tree storage: If the number of points is large, you need to use vector storage
vector<int> G[MAXN]; void Read_tree () { int u,v; scanf ("%d",&N); for (i=1; i<=n-1; i++) { scanf ("%d%d",& u,&v); G[u].push_back (v); G[v].push_back (u); } }
2. Conversions: Conversions are done by a Dfs that fills the fa[in recursion]
void dfs (int u,int father) {// OK tree with u as root, Father is U's father int d=g[u].size (); for (int i= 0 ; I<d;i++) { int v=g[u][i]; if (v!=father) // Prevent backwards search back, enter the dead loop dfs (V,FA[V]=U); // recursion + Assignment
3. Small details: Initialize the time to make fa[root]=-1, meaning root without father, call is Dfs (ROOT,-1)
No root tree transforms into a root tree