#include <stdio.h> #include <string.h> #include <stdlib.h> #include <vector> #include < Algorithm> #define N 100000+2using namespace std;//No root tree to root tree algorithm/* Algorithm analysis: So-called no root tree, is the root node arbitrary tree. We can identify a root node for it. We can assume that a node is the root node, and then start the DFS or BFS search from that node, and in the process of searching, record a father[] array as the record path, which is used to record the parent node of the current node. The algorithm is very simple, need to pay attention to two places: (* *. Set the root node father[root]=-1; Indicates that the root node does not have a parent node (*2.BFS or DFS in the search process, determines whether the encountered point is not the root node, and then the parent node is specified. If it is the root node, do not modify, if you forget to judge this condition, will cause infinite recursion (Dfs) or infinite loop (BFS) */int N; N nodes, n-1 edge, vector create two-dimensional array storage (dynamic storage can be stored regardless of storage size) Vector<int>q[n];int Fa[n]; Record parent node information void Dfs (int u, int father)//recursive conversion with U as root node, u parent node is father{int len=q[u].size ();//traverse point for (int i=0; i<le) connected to the point N i++) {int v=q[u][i];///Get the point if (v!=father)//* determine if V and its parent are the same, otherwise cause an infinite loop of Dfs (V, fa[v]=u);//Set the parent node of V For u, and then recursively convert the subtree of the V node to}}int Main () {scanf ("%d", &n); int u, v; for (int i=0; i<n-1; i++) {scanf ("%d%d", &u, &v); Q[u].push_back (v); Q[v].push_back (U); }//For DFs transformation has root tree fa[1]=-1; DFS (1,-1); return 0;}
Talk about tree---No root tree go to a root tree (Dfs search conversion +FA array Record parent node) * "Template"