LCA (recent public ancestor)--tarjan offline algorithm HDU 2586

Source: Internet
Author: User

HDU 2586 how far away?

Time limit:2000/1000 MS (java/others) Memory limit:32768/32768 K (java/others)
Total submission (s): 11320 Accepted Submission (s): 4119

Problem Description There is n houses in the village and some bidirectional roads connecting-them. Every day peole "What is it if I am want to go from House A to house B"? Usually it hard to answer. But luckily int this village the answer was always unique, since the roads was built in the the-the-the-that-there is a unique simp Le path ("simple" means you can ' t visit a place twice) between every the houses. Yout task is to answer all these curious people. Inputfirst line was a single integer T (t<=10), indicating the number of test cases.
For each test case,in the first line there is the numbers N (2<=n<=40000) and M (1<=m<=200), the number of hous Es and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning this there is a road con Necting House I and House j,with length K (0<k<=40000). The houses is labeled from 1 to N.
Next m lines each have distinct integers i and j, you areato answer the distance between House I and House J Outputfor EAC H test case,output m lines. Each line represents the answer of the query. Output a bland line after all test case. Sample Input23 2 103 1 151 2 1001 1 Sample Output1025100100 Sourceecjtu Spring Contest parse: Tarjan offline algorithm for L CA: Concept Description:

LCA (Least Common Ancestors): A recent public ancestor, refers to the problem of finding the nearest common ancestor (the one that is farthest from the root) of all ancestors of the two nodes U and V in the root tree.

Complexity of time and space:
    • Time complexity: When the number of queries is Q and the node count is N, the time complexity is O (n+q).
    • Spatial complexity: The amount of space stored when ① is built (the number of nodes in a tree), the amount of space required to traverse a tree when ② deep (the maximum depth of the tree)

The algorithm is implemented based on basic principles:

The algorithm is implemented based on DFS and check sets .

Algorithm flow and proof of LCA (U,V):
  1. From the root node (root) , start deep Search,
  2. For a newly searched node (x), first create a collection of the nodes (maintained by the par array, par[x]=x, the current set of only element x),
  3. It then searches for and processes all subtrees contained in the node (search and processing are recursive processes.) combined with the 5th understanding: after each search for a subtrees tree, you can determine that the LCA query in the subtree has been solved, and the results of other LCA queries must be outside the subtree. )
  4. When all subtrees of the node have been searched, the par[x]= of the current node (the Father node of x) is turnedback (thecollection is merged)
  5. Then start processing all the queries and the LCA (U,?) that were included in all the Queries . (it embodies the offline algorithm , which reorganizes the order of the nodes which are traversed when the inquiry order is deep search)
    • In the query that contains the node, first determine whether the other node (v) in the currently processing query (U,V) has also been traversed,
    • If it has not been traversed, it is temporarily not processed ; otherwise LCA (u,v) = Findpar (Par[v])(and set). (proof: Because V is traversed before traversing to u (that is, the current x node). If there is a query from the current node (U) to Node V, and V has been checked, the nearest public ancestor of the current node and V must have not been examined due to a deep-first search, and this recent common ancestor's inclusion v subtree must have been searched, Then this recent public ancestor must be the ancestor of the set of V. )
    • All queries that contain this node are all processed

< The sequential comprehension of the merging of the combined traversal and the check set, see Figure >

Process LCA (3,4): Because 3 is accessed before traversing to 4, so LCA (3,4) =findpar (par[3]) = 3; (At this time the inquiry operation for LCA (4,5) is temporarily skipped.

Process LCA (5,4): LCA (5,4) =find (par[4]) =2 because 4 is accessed in traversal to 5

Extension: Finding the shortest distance between two points (u,v) on a tree

Method of finding the shortest distance between two points in a tree u,v: Dis[u] is the distance from the U to the root node

Then the distance between the U to V: ans[u][v]=dis[u]+dis[v]-2*dis[lca[u][v]] (minus twice times the public distance from the root node);

Exercises

1#include <cstring>2#include <iostream>3 using namespacestd;4#include <cstdio>5 #defineM 2016#include <vector>7 #defineN 401008Vector <int> Que[n];/*Store Query Queue*/9 intANS[M];/*Save the answer.*/Ten intn,m,u,v,k; One structedge{ A     intV,last,w;/*Edge Table*/ -}edge[n*2]; - inthead[n],dis[n]={0}; the intt,t=0; - intFather[n],ance[n];/*Father[n] represents the current processing subtree, ance represents the current ancestor of this point*/ - BOOLVisit[n],root[n];/*visit determine whether the current point of the subtree LCA has been sought, Root is looking for the root node*/ - voidAdd_edge (intUintVintW) + { -++T; +edge[t].v=v; Aedge[t].w=W; atedge[t].last=Head[u]; -head[u]=T; - } - voidinput () - { -memset (Visit,false,sizeof(visit)); inmemset (Root,false,sizeof(root)); -Memset (Head,0,sizeof(head)); tomemset (DIS,0,sizeof(DIS)); +Memset (Edge,0,sizeof(Edge)); -scanf"%d%d",&n,&m); the      for(intI=1; i<=n-1;++i) *     { $scanf"%d%d%d",&u,&v,&k);Panax Notoginseng Add_edge (u,v,k); -root[v]=true; theAnce[i]=i;/*Initialize*/ +father[i]=i; A     } the      for(intI=1; i<=m;++i) +     { -scanf"%d%d",&u,&v); $Que[u].push_back (i);/*because the offline algorithm can not know his query order, but we have to follow the order of the query output, so in the query sequence of the even digits of the next bit in the order of the ANS*/ $ Que[u].push_back (v); - Que[v].push_back (i); - que[v].push_back (u); the     } - }Wuyi intFindintx) the { -     return(father[x]==x)? father[x]:father[x]=find (Father[x]); Wu } - voidTarjan (intKintW) About { $ance[k]=K; -dis[k]=W; -      for(intL=head[k];l;l=edge[l].last) -     { ATarjan (edge[l].v,dis[k]+EDGE[L].W); +Father[edge[l].v]=k;/*father the collection of the current point and all of the subtree, while the ancestor of the direct point of the tree is set to K, so when querying a sub-tree of points on the interval, first use Find to find the representative elements, and then seek the ancestors*/ theance[edge[l].v]=K; -     } $visit[k]=true; the     intSize=que[k].size (); the      for(intI=1; i<size;i+=2) the     { the         if(Visit[que[k][i]])/*if the LCA of another point on this side has been calculated, then the ancestor of the set is the nearest public ancestor of these two points.*/ -         { in             intzu=Ance[find (Que[k][i]); theans[que[k][i-1]]=dis[k]+dis[que[k][i]]-2*Dis[zu]; the         } About     } the } the intMain () the { +scanf"%d",&T); -      while(t--) the     {Bayi input (); the          for(intI=1; i<=n;++i) the         { -             if(!root[i])/*deep Search starting from the root node*/ -             { theTarjan (I,0); the                  Break; the             } the         } -          for(intI=1; i<=m;++i) theprintf"%d\n", Ans[i]); the     } the     return 0;94}

LCA (recent public ancestor)--tarjan offline algorithm HDU 2586

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.