A recent topic, presumably, is to find the nearest common ancestor of two nodes in a multi-fork tree, and the input is represented by an adjacency matrix.
To understand the Tarjan algorithm and implement it, you need to understand the content first:
1) Depth-first search; The core idea of the Tarjan algorithm: When a node has just been searched, to see if its associated nodes v has been accessed, if V has been visited, then their nearest public ancestor is the ancestor of V.
2) and find out the principles and methods of implementation, and the representative of the collection and the difference between the ancestors (in fact, can also be expressed together), the ancestors of the update time
3) How to represent the multi-fork number (adjacency list, adjacency matrix), how to represent the query pair, how to record the query results
The following is the C + + implementation code, lazy, each call to query a function. The data structure of the query pair can be represented by the adjacency table mentioned below.
#include <vector>#include<string>#include<algorithm>#include<iostream>using namespacestd;classlca{ Public: LCA (Constvector<string> &vstr): Str (VSTR), F (vstr.size (),-1), Ancestor (Vstr.size (),-1), visit (Vstr.size (),0) { } intLca_query (intVertexintUintv) { Static intans=-1; Ancestor[vertex]=Vertex; Visit[vertex]=true; for(inti =0; I < str.size (); ++i) { if((str[vertex][i] = ='1') && (visit[i] = =0) ) {ans=Lca_query (i, U, v); Unite (vertex, i); Ancestor[find (vertex)]=Vertex; } } if(Vertex = = u&&Visit[v]) ans=Ancestor[find (v)]; if(Vertex = = v&&Visit[u]) ans=ancestor[find (u)]; returnans; }Private: Constvector<string> &str; Vector<int> f;//and check Setvector<int>ancestor; Vector<BOOL>visit; intFindinti) {if(F[i] = =-1) returni; returnF[i] =find (F[i]); } voidUniteintUintv) {intx =find (U); inty =Find (v); if(X! =y) f[x]=y; }};intmain () {vector<string> v123 = {"01100001","10011000","10000000","01000000","01000110","00001000","00000100","10000000" }; LCA Query1 (v123); cout<< Query1.lca_query (0,4,7);}
In fact, it is a waste of time to use the adjacency matrix to represent the multi-fork number, a single multi-fork tree as a non-circular graph, only (n-1) edge, where n is the number of nodes. There are good ways to represent contiguous lists on the web,
struct edge{ int2]; int HEAD[MAXN], tot; void Addedge (intint v)// adjacency Header insertion method plus edge { = v; = Head[u]; = tot++;}
is essentially a single-linked list, but the next pointer to the single-linked list is just an array of subscript values. Head[u] records the bottom of an array of edges that were last started from U.
To understand the Tarjan algorithm, we must first understand and check the set
Recent public ancestor Tarjan offline algorithm C + +