LCA basis

https://www.luogu.org/problemnew/solution/P3379

LCA is called the minimum common ancestor, to find the nearest point of a common two tree nodes;

Common multiplication algorithm:

#include<iostream>
#include<cstdio>
#include<vector>
using namespace std;
const int N=1E6+7;
long long bits[30];
int depth[N],fa[N][30];
Vector < int > VE [N];
 // "preprocessing section --------- ---------" 
void inint () {
    bits [ 0 ] = . 1 ;
     for ( int i = . 1 ; i < 30 ; i ++) bits [i] = bits [I- . 1 ] << . 1 ; // with an array of recording the i-th power of 2, each up satisfying the condition of maximum climb power 2 i 
}
 void DFS ( int X, int Y) { // X child node, y parent node 
    depth [X] = depth [Y] + . 1 ; // child node and the parent node relationships 
    FA [X] [ 0 ] = Y;
     // "---- one of the core -" 
    for ( int I = . 1 ; I < 30; i ++) FA [X] [i] = FA [FA [X] [I- . 1 ]] [I- . 1 ]; 
     // "-------" each time the power climb i 2 equivalent 2 in the first climb power of i-1, i-1 climbing power of 2 
    for ( int I = 0 ; I <VE [x] .size (); I ++) { // temporary memory table access and x in FIG. point out the associated child node is a parent node. The parent excluded 
        int X1 = VE [X] [I];
         IF (! X1 = Y) {
            the DFS (x1, x); // let the parent do x, x1 do child node 
        }
    }
}
// "-----------------------------------" 
int LCA ( int X, int Y) { / / we require deeper point x is, y is a shallow point 
    IF (depth [x] <depth [Y]) the swap (x, y); // if the depth [x], then ,, be exchanged small click; 
    int DIF depth = [X] - depth [y]; 
     for ( int I = 29 ; I> = 0 ; i-- ) {
         IF (DIF> = bits [I]) { // the variable X and y to the same height. The result is equivalent to dividing binary dif then recorded at the position of x at this time 
            x = FA [x] [I];
            dif=dif-bits[i];
        }
    }
    IF (x == Y) return x; // if they are equal on the same side of both the branch instructions, y, x is the nearest to the root 
    for ( int I = 29 ; I> = 0 ; i-- ) {
         IF (depth [x]> = bits [I] && FA [x] [I]! = FA [y] [I]) { // find the root of x and y a first child node 
            x = FA [x] [ i];
            y=fa[y][i];
        }
    }
    return FA [X] [ 0 ]; // return to their own child nodes parent node is a common root 
}

int main () {
    inint ();
    int n,m,s;
    scanf("%d%d%d",&n,&m,&s);
    int x,y;
    for(int i=1;i<=n-1;i++){
        scanf("%d%d",&x,&y);
        ve[x].push_back(y);
        ve[y].push_back(x);
    }
    DFS (s, 0 ); // where s is the total of the root, if we predetermined bounds, referred to as 0, such as cross-border on the parent node s, and recording is 0; 
    for ( int I = . 1 ; I <= m; I ++ ) {
        scanf("%d%d",&x,&y);
        printf("%d\n",lca(x,y));
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/Accepting/p/11322155.html
lca