"Graph theory" LCA recent public ancestor __ graph theory

Source: Internet
Author: User

Reprint remember to tell Chin-Qian Oh ~

Sync Update: https://www.dreamwings.cn/lca/4874.html Overview

LCA (least Common ancestors), a recent public ancestor, refers to the problem of finding the nearest common ancestor of two nodes, U and V, in a tree with roots.

LCA can be divided into online algorithm and off-line algorithm online algorithm: The program can be serialized in a way of processing input, that is, in the beginning does not need to know all the input. offline algorithm: refers to all the input data that needs to be known at the outset and outputs the result immediately after solving a problem.

Algorithm Chapter

For this problem, it is easy to think of a way to backtrack from U and V to the root node, the first intersection of these two paths, then, is the nearest common ancestor of U, V, in a balanced binary tree in which the time complexity of the algorithm can reach O (logn) O (\log N), but for some trees that degenerate into chains, The algorithm has the worst time complexity of O (n) o (n), and obviously cannot satisfy the higher frequency query.

This section introduces several more efficient algorithms to solve this problem, there are three kinds of common algorithms: Online DFS + ST algorithm, multiplication algorithm, off-line Tarjan algorithm.

Next we come to one by one to explain the three kinds of * * Seemingly advanced, in fact, is not simple * * algorithm.

many pictures ahead. Qian-Chin did not know whether to issue a warning. (; ′⌒ ') (Escape

online DFS + ST algorithm

First see what you will think of ST. (Brain for a long time did not think it will be the abbreviation of which word)

Read the previous "data structure" RMQ problem, you can understand the idea of St algorithm ~

So, this on-line algorithm about LCA can also be built on the basis of RMQ problems.

We set up LCA (T,U,V) as the most recent common ancestor of node U and V in the root tree T, RMQ (a,i,j) as the smallest (large) value on the interval [i,j] of the linear sequence A.

The following figure has a root tree:

We make the node number meet the parent node number less than the child node number (number criteria)

It can be seen that LCA (t,4,5) = 2, LCA (t,2,8) = 1, LCA (t,3,9) = 3.

Set the linear sequence A to the sequence traversal of the root tree T, i.e. a = [4,2,5,1,8,6,9,3,7].

By the nature of the middle-order traversal, we can know that the nearest common ancestor of any two-point u, V is always in the interval with the endpoint at the location of the two point, and the number is the smallest.

give me a chestnut:

Assuming that u = 8, V = 7, the interval defined by the two points is [8,6,9,3,7], and the interval minimum is 3, that is, node 3 is the nearest common ancestor of U and v.

To solve the interval maximum value problem, we can use ST algorithm in RMQ problem.

But the nodes given in some of the questions do not necessarily satisfy the number of parent nodes that we say are less than the child nodes. So we can use the relationship between the nodes to build the graph, and then use the previous sequence to renumber each node to generate a linear sequence A, so the problem is converted to the interval of the most value of the query, and the same practice before the ~ ~

time Complexity: Nxo (Logn) Nxo (\log N) pretreatment + O (1) O (1) query

To understand the RMQ problem of the solution can poke the link above oh ~

The above section describes how LCA translates into RMQ problems, and in practice the two schemes can be transformed from one to the other.

Before analogy, how do we convert a linear sequence into a root tree that satisfies the number criteria ? The minimum value in the set sequence is AK A_k, the root node of the priority is AK A_k TK T_k will a[1...k−1] a[1...k-1] Recursive contribution as the TK t_k Zuozi A[K+1...N] A[K+1...N] recursive contribution as TK T The right subtree of _k

The reader can try to use this method to construct the previous linear sequence A = [4,2,5,1,8,6,9,3,7] with the root tree T, the result must satisfy the previously mentioned number condition , but not necessarily unique.

Off-line Tarjan algorithm

Tarjan algorithm is a common off-line algorithm to solve the LCA problem, it combines depth first search and lookup set, the whole algorithm is linear processing time.

first, introduce the basic idea of Tarjan algorithm: Select a node as the root node, start at the root node to traverse the point u all child node V, and Mark V has been visited if there are child nodes, return 2, otherwise the next step merge V to u in the collection to find the current Point you have inquired about the point E if E has been visited, you can determine that the nearest common ancestor of U and E is the parent node of E merged into

Pseudo Code:

Tarjan (U)               //merge and find is the collection merge function and lookup function
{for
    each (U,V)       //Traversal U of all sub nodes v
    {
        Tarjan (v);      Continue traversing the
        merge (u,v);     Merge V to u this set
        tag v has been accessed;
    }
    For each (u,e)       //traversal of all relationships with U e
    {
        if (e has been accessed)
            u, E's nearest common ancestor is find (e);
    }

Feel that there is no other content, but there must be a lot of people do not understand how to do it.

even if Qian-chin does not want to draw so many pictures, but still first issued the warning before (☆▽☆)

Let's assume that the Tarjan process is simulated in the following tree (fewer nodes can draw less graph O ( ̄▽ ̄) o)

Query exists: LCA (t,3,4), LCA (t,4,6), LCA (t,2,1).

Note: Each node's color represents which set it currently belongs to, the Orange Line is the search path, and the black line is the merged path.

Current location is U = 1, not traversing child set V = {2,5}, traversing down.

Current location is U = 2, not traversing child set V = {3,4}, traversing down.

The current location is U = 3, not traversing the child set V = {}, recursively reaching the lowest level, traversing all related queries to discover the existence of LCA (t,3,4), but node 4 is not accessed at this time, so nothing is done and the layer recursively ends.

Recursive return, current location U = 2, merge nodes 3 to u collection, tag vis[3] = True, the Child collection V = {4} is not traversed, and the traversal is traversed.

Current Location U = 4, not traversing child set V = {}, traversing all related queries to discover the existence of LCA (t,3,4), and vis[3] = True, at which point the solution to the query is the leader of the set of Node 3, LCA (t,3,4) = 2; LCA (t,4,6), but node 6 is not accessed at this time, so nothing is done. The layer recursively ends.

Recursive return, current position u = 2, merge node 4 to u collection, tag vis[4] = True, not traversing child set V = {}, traversal related query discovers LCA (t,2,1), but node 1 is not accessed at this time, so nothing is done, and the layer recursively ends.

Recursive return, current location U = 1, merge nodes 2 to u collection, tag vis[2] = True, No Child collection V = {5}, continue traversing down.

Current Location U = 5, not traversing child collection V = {6}, continue traversing down.

Current Location U = 6, not traversing child set V = {}, traversal related query finds existence of LCA (t,4,6) and vis[4] = true, so the solution to the query is the leader of the set of Node 4, LCA (t,4,6) = 1, which ends recursively.

Recursive return, current location U = 5, merge Nodes 6 to U collection, and Mark vis[6] = true, not traversing child collection V = {}, no related query so this layer recursively ends.

Recursive return, current location U = 1, merge nodes 5 to u collection, and Mark vis[5] = True, not traversing the child set V = {}, traversing the query discovers the existence of LCA (t,2,1), at which point the solution is the leader of the set of Node 2, that is, the LCA (T , 2, 1) = 1, recursion ends.

So the whole Tarjan algorithm is over.

PS: Do not care about the end of the root node color and the other node color a little bit of a gap, may be thousands of times in the stain did not look carefully, in short, so slightly ~

PPS: The so-called leader is, is the leader!

Multiplication Algorithm

Wow. There is also a multiplier algorithm to continue to add it later.

Summary Article

We can choose different algorithms for different LCA problems.

If a tree has dynamic update, then off-line algorithm is a bit powerless, but in other cases, off-line algorithm is often more efficient (although not guaranteed to get the order of the solution and input consistent, but we have sort AH)

In short, like which style of code is our own will slightly ~

In addition, LCA and RMQ problems are two very basic problems, many complex problems can be translated into these two types of problems to solve. (Of course, these two types of problems can also be converted to each other ~)

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.