Advertisement
Dang_Quan_10_Tin

Find Centroid

Nov 8th, 2020
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. const int N = 1e5 + 2;
  2. int cnt[N];
  3. vector<pair<int, int>> adj[N];
  4. bool inused[N];
  5.  
  6. void dfs_cnt(int v, int p = -1)
  7. {
  8.     cnt[v] = 1;
  9.     for (auto i : adj[v])
  10.         if (i.first != p && inused[i.second])
  11.             dfs_cnt(i.first, v),
  12.                 cnt[v] += cnt[i.first];
  13. }
  14.  
  15. int Find_Centroid(int root)
  16. {
  17.     dfs_cnt(root);
  18.     int centroid = root;
  19.     while (1)
  20.     {
  21.         int t, v = 0;
  22.         for (auto i : adj[centroid])
  23.             if (inused[i.second] && cnt[i.first] <= cnt[centroid])
  24.             {
  25.                 if (cnt[i.first] > v)
  26.                 {
  27.                     v = cnt[i.first];
  28.                     t = i.first;
  29.                 }
  30.             }
  31.         if (v <= cnt[root] / 2)
  32.             return centroid;
  33.         centroid = t;
  34.     }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement