No root tree transforms into a root tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.