Doubling method seek common ancestor notes and organize ideas

The core of a two-dimensional array father: father [i] [j] stored in the i-th point jump up point j ^ 2 times of arrival

      The father [i] [0] indicates the father of point i,

             [I] [. 1] i represents two upwardly,

             [I] [2] i represents four upwardly.

Once arrays, and dep father DFS maintenance and so on.

See Detailed function body:

int the LCA ( int x, int Y) {
     IF (DEP [x] <DEP [Y]) the swap (x, Y);   // ensure x D to Y 
    int T DEP = [x] - DEP [Y];   / / T of the same depth x y skip number of steps required 
    for ( int I = 0 ; I <= 20 is ; I ++ )
         IF (( . 1 << I) & T) x = Father [x] [I];  
       // 1 left and the i-th bit t t can be drawn on whether binary bit 1 Dir i
       // if x is 1 then jump up bit 2 ^ i, t bits just jumped entire cycle 
        
    iF (x = y =) return x; // has whether y is equal to x ancestor, i.e., the same jump height 
    
    for ( int I =20 is ; I> = 0 ; I -) {   // x and y simultaneously jump up 
        IF (Father [x] [I] == Father [y] [I]) Continue ;  
               // if x and y ^ 2 hops after the bit is already equal to i, the at least one multi-hop, this step does not jump 
        X = Father [X] [I]; y = Father [y] [I];
               // X and y position jump up after 2 ^ i not equal, the jump bits 2 ^ i 
    }   // the x and y should be in the dance through "just not equal to" the number of layers, i.e. one common ancestor in its 
    
    return Father [x] [ 0 ];   // returns his father is the most recent common ancestor 
}

 

Guess you like

Origin www.cnblogs.com/miserweyte/p/11362026.html