_no0B

Untitled

Mar 18th, 2020
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. /// HLD + LCA
  2. /// call  hld(n)
  3. vector < int > v[N];
  4. bool mark[N];   /// 0 for light edges and 1 for heavy
  5. int deg[N], par[logn+2][N], lv[N], last[N], id[N], path[N], cnt;  /// last[n] = node with the lowest depth which lies on the same heavy path as node n
  6. queue < int > q;
  7. int findpar(int n, int k){
  8.     for(int i = 0; k>0; i++){
  9.         if(k&(1<<i)){
  10.             k -= (1<<i);
  11.             n = par[i][n];
  12.         }
  13.     }
  14.     return n;
  15. }
  16. int lca(int a, int b){
  17.     if(lv[a]>lv[b]) swap(a,b);
  18.     b = findpar(b,lv[b]-lv[a]);
  19.     if(a==b) return a;
  20.     for(int i = logn; i>=0; i--){
  21.         if(par[i][a]!=par[i][b]){
  22.             a = par[i][a];
  23.             b = par[i][b];
  24.         }
  25.     }
  26.     return par[0][a];
  27. }
  28. int dfs(int n, int p){
  29.     par[0][n] = p;
  30.     lv[n] = lv[p]+1;
  31.     deg[n] = 0;
  32.     int cntt = 1, mx = 0, b = 0;
  33.     for(int i = 0; i<v[n].size(); i++){
  34.         int a = v[n][i];
  35.         if(a!=p){
  36.             deg[n]++;
  37.             int tmp = dfs(a,n);
  38.             cntt += tmp;
  39.             if(mx<tmp){
  40.                 mx = tmp;
  41.                 b = a;
  42.             }
  43.             mark[a] = 0;
  44.         }
  45.     }
  46.     if(mx*2>=cntt){
  47.         mark[b] = 1;
  48.     }
  49.     return cntt;
  50. }
  51. int fun(int n){
  52.     path[n] = cnt++;
  53.     id[path[n]] = n;
  54.     if(mark[n]==0){
  55.         deg[par[0][n]]--;
  56.         if(deg[par[0][n]]==0) q.push(par[0][n]);
  57.         last[n] = n;
  58.     }
  59.     else last[n] = fun(par[0][n]);
  60.     return last[n];
  61. }
  62. void hld(int n){
  63.     mark[1] = 0;
  64.     dfs(1,0);
  65.     for(int i = 1; i<=n; i++) if(deg[i]==0) q.push(i);
  66.     cnt = 1;
  67.     while(!q.empty()){
  68.         int a = q.front();
  69.         q.pop();
  70.         fun(a);
  71.     }
  72.     for(int i = 1; i<=logn; i++)
  73.         for(int j = 1; j<=n; j++) par[i][j] = par[i-1][par[i-1][j]];
  74. }
Advertisement
Add Comment
Please, Sign In to add comment