Advertisement
LinKin

LCA

Jun 22nd, 2013
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. /*
  2.  * Algorithm : Lowest Common Ancestor ( Adapted From Topcoder )
  3.  * Order : Pre-proccesing O( nlogn )
  4.            Query O( logn )
  5.  * Note : Node indexing must be 0 based
  6.  */
  7.  
  8. #include<stdio.h>
  9. #include<string.h>
  10. #include<vector>
  11. #include<algorithm>
  12. using namespace std;
  13. #define MAX 100007
  14. #define MAX_L 21
  15. long N;
  16. long Pre[MAX+7][MAX_L];
  17. long Par[MAX+7];
  18. long Lvl[MAX+7];
  19.  
  20. void Process( void )
  21. {
  22.     long i,j;
  23.     for( i=0;i<N;i++ ){
  24.         for( j=0;1<<j<N;j++ ) Pre[i][j] = -1;
  25.     }
  26.     for( i=0;i<N;i++ ) Pre[i][0] = Par[i];
  27.     for( j=1;1<<j<N;j++ ){
  28.         for( i=0;i<N;i++ ){
  29.             if( Pre[i][j-1] != -1 ){
  30.                 Pre[i][j] = Pre[Pre[i][j-1]][j-1];
  31.             }
  32.         }
  33.     }
  34. }
  35.  
  36. long Query( long p,long q )
  37. {
  38.     long i,Log;
  39.  
  40.     /* If p is situated on a higher level than q then swap them */
  41.     if( Lvl[p]<Lvl[q] ) swap( p,q );
  42.     /* Compute the value of [log(Lvl[p)] */
  43.     for( Log=1;1<<Log <= Lvl[p];Log++ );
  44.     Log--;
  45.  
  46.     /* Find the ancestor of node p situated on the same level
  47.        with q using the values in Pre */
  48.     for( i=Log;i>=0;i-- ){
  49.         if( Lvl[p] - (1<<i) >= Lvl[q] ) p = Pre[p][i];
  50.     }
  51.     if( p==q ) return p;
  52.  
  53.     /* Compute LCA(p, q) using the values in Pre */
  54.     for( i=Log;i>=0;i-- ){
  55.         if( Pre[p][i]!=-1 && Pre[p][i]!=Pre[q][i] ){
  56.             p = Pre[p][i];
  57.             q = Pre[q][i];
  58.         }
  59.     }
  60.     return Par[p];
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement