Advertisement
LinKin

HLD

Nov 17th, 2011
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.03 KB | None | 0 0
  1. /*
  2.     Algorithm: heavy-light decompositon
  3.     Order: O(N) / O(nlogn) if any update is needed
  4. */
  5.  
  6. #include<stdio.h>
  7. #include<string.h>
  8. #include<vector>
  9. #include<algorithm>
  10. using namespace std;
  11.  
  12. #define MAX 30007
  13.  
  14. long N; // number of node in tree
  15. vector<long> Edge[MAX+7];
  16. long SubT[MAX+7]; // subtree size
  17. long Par[MAX+7]; // parent of a node
  18. long Level[MAX+7]; // level of a node
  19.  
  20. long nC; // number of chain
  21. long ChainLdr[MAX+7]; // chainleadr of a node
  22.                       // for light edge chainldr is that node
  23. long Chain[MAX+7];    // node v in is which chain
  24. long nP;            // number of position , obviously == N
  25. long Pos[MAX+7];    // Pos of a node in chain/dfs order
  26.  
  27. /* find subtree size and level */
  28. long Explore( long u,long p,long l )
  29. {
  30.     SubT[u] = 1;
  31.     Par[u] = p;
  32.     Level[u] = l;
  33.     long i;
  34.     for( i=0;i<Edge[u].size();i++){
  35.         long v = Edge[u][i];
  36.         if( p==v ) continue;
  37.         SubT[u] += Explore( v,u,l+1 );
  38.     }
  39.     return SubT[u];
  40. }
  41. /* if IsL make this node a chainledr of new chain */
  42. void HeavyLight( long u,long k,bool IsL )
  43. {
  44.     if( IsL ){
  45.         k = ++nC;
  46.         ChainLdr[k] = u;
  47.     }
  48.     Chain[u] = k;
  49.     Pos[u] = ++nP;
  50.     //Update( nP,W[u] ); if query is need can b updated here    
  51.     long i,mx = -1; // max subtree size child is mx
  52.     for( i=0;i<Edge[u].size();i++){
  53.         long v = Edge[u][i];
  54.         if( Par[u]==v ) continue;
  55.         if( mx==-1 ) mx = v;
  56.         else if( SubT[v] > SubT[mx] ) mx = v;
  57.     }
  58.     if( mx==-1 ) return;
  59.     HeavyLight( mx,k,false );
  60.     for( i=0;i<Edge[u].size();i++){
  61.         long v = Edge[u][i];
  62.         if( Par[u]==v || mx == v ) continue;
  63.         HeavyLight( v,0,true );
  64.     }
  65. }
  66.  
  67. long LCA( long u,long v )
  68. {
  69.     while( Chain[u]!=Chain[v] ){
  70.         if( Level[ChainLdr[Chain[u]]] < Level[ChainLdr[Chain[v]]] ){
  71.             v = Par[ChainLdr[Chain[v]]];
  72.         }
  73.         else{
  74.             u = Par[ChainLdr[Chain[u]]];
  75.         }
  76.     }
  77.     if( Level[u] < Level[v] ) return u;
  78.     else return v;
  79. }
  80.  
  81.  
  82. int main( void )
  83. {
  84.     //freopen("text1.txt","r",stdin );
  85.     // node is index from 0
  86.     scanf("%ld",&N );
  87.     Explore( 0,0,0 );
  88.     HeavyLight( 0,0,true );
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement