Advertisement
Jasir

LCA

Jun 15th, 2018
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. vector <int> g[mx];
  2. int T[mx], P[mx][22], L[mx];
  3.  
  4. void dfs(int from,int u,int dep){
  5.     T[u]=from;
  6.     L[u]=dep;
  7.     for(int i=0;i<(int)g[u].size();i++){
  8.         int v = g[u][i];
  9.         if(v==from) continue;
  10.         dfs(u,v,dep+1);
  11.     }
  12. }
  13.  
  14. int lca_query(int N, int p, int q){
  15.     if (L[p] < L[q]) swap(p, q);
  16.     int log = 1;
  17.     while(1){
  18.         int next=log+1;
  19.         if((1<<next)>L[p])break;
  20.         log++;
  21.     }
  22.     for(int i=log;i>=0;i--){
  23.         if (L[p] - (1 << i) >= L[q]){
  24.             p = P[p][i];
  25.         }
  26.     }
  27.  
  28.     if (p == q)
  29.         return p;
  30.  
  31.     for(int i = log; i >= 0; i--){
  32.         if(P[p][i] != -1 && P[p][i] != P[q][i]){
  33.             p = P[p][i], q = P[q][i];
  34.         }
  35.     }
  36.     return T[p];
  37. }
  38.  
  39. int qthparetn(int N, int p, int q){
  40.     int log = 1;
  41.     while(1){
  42.         int next=log+1;
  43.         if((1<<next)>L[p])break;
  44.         log++;
  45.     }
  46.     for(int i = log; i >= 0; i--){
  47.         if((1<<i)<=q){
  48.             p = P[p][i];
  49.             q -= (1<<i);
  50.         }
  51.     }
  52.     return p;
  53. }
  54.  
  55. int dis(int a, int b, int n){
  56.     int c = lca_query(n, a, b);
  57.     return L[a] + L[b] - 2*L[c];
  58.  }
  59.  
  60. void lca_init(int N){
  61.     memset (P,-1,sizeof(P));
  62.     dfs(-1, 0, 0);
  63.     for(int i = 0; i < N; i++){
  64.         P[i][0] = T[i];
  65.     }
  66.     for(int j=1;1<<j<N;j++){
  67.         for(int i=0;i<N;i++){
  68.             if(P[i][j-1]!=-1){
  69.                 P[i][j] = P[P[i][j-1]][j-1];
  70.             }
  71.         }
  72.     }
  73.  }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement