Title Link: http://poj.org/problem?id=1330
Test instructions: Given a root tree of n nodes, as well as the two nodes in the tree u,v, the nearest public ancestor of U,v is obtained.
Data range: N [2, 10000]
Idea: Starting from the root of the post-depth priority traversal, set the VIS array real-time records have been accessed.
After each traversal of a subtrees tree R, it is incorporated into the set of the parent node P of R as the representative of the meta. At this point P is not the required U, v node, if r==u, and V has been visited, then the LCA (U, v) must be the representative of the set of V. The situation of p==v is similar.
My first LCA problem of the Tarjan algorithm, the topic only a set of queries, the implementation is very concise.
Note the title to the tree format: give the n-1 number to <u, v>,u to the parent node of V. As a result, the adjacency table can be stored as a graph, while the entry of each node is recorded, and the point with a degree of 0 is the root.
1#include <cstdio>2#include <cstring>3#include <vector>4 using namespacestd;5 Const intMax_n =10005;6 intParent[max_n];7 voidinit () {8 for(intI=0; i<max_n; i++){9Parent[i] =i;Ten } One } A intFindintx) { - if(Parent[x] = = x)returnx; - returnPARENT[X] =find (Parent[x]); the } - voidUniteintXinty) { -x =find (x); -y =find (y); + if(x = = y)return ; -Parent[y] =x; + } A BOOLSame (intXinty) { at returnFind (x) = =find (y); - } -vector<int>G[max_n]; - intu, v; - intT; - intN; in intVis[max_n]; - intIndeg[max_n]; to voidDfsintR) { + //printf ("%d\n", r); - for(intI=0; I<g[r].size (); i++){ the if(!Vis[g[r][i]]) { * DFS (G[r][i]); $Unite (R, G[r][i]);//Child Merge to parent nodePanax Notoginseng } - } theVIS[R] =1;//Post-post traversal + if(R = = U &&Vis[v]) { Aprintf"%d\n", find (v)); the return ; +}Else if(r = = v &&Vis[u]) { -printf"%d\n", find (U)); $ return ; $ } - } - voidLCA () { thememset (Vis,0,sizeof(Vis)); - init ();Wuyi intR =0; the for(intI=1; i<=n; i++){ - if(indeg[i]==0){ Wu //printf ("Root:%d\n", i);//the degree of 0 is the root of the tree - DFS (i); About } $ } - } - intMain () - { Ascanf"%d", &T); + while(t--){ thescanf"%d", &n); -memset (Indeg,0,sizeof(indeg)); $ for(intI=0; i<max_n; i++) g[i].clear (); the for(intI=0; i<n-1; i++){ thescanf"%d%d", &u, &v); theG[u].push_back (v);//a map of the direction theindeg[v]++; - } inscanf"%d%d", &u, &v); the LCA (); the } About return 0; the}
POJ 1330 Nearest Common Ancestors (LCA Tarjan algorithm)