Advertisement
ivnikkk

Untitled

May 22nd, 2022 (edited)
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.46 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #define debug(l) cerr<<#l<<' '<<l<<'\n';
  3. #include "bits/stdc++.h"
  4. using namespace std;
  5. #define all(a) a.begin(), a.end()
  6. typedef int ll;
  7. typedef pair<ll, ll> pll;
  8. typedef long double ld;
  9. vector<vector<ll>> gr;
  10. struct Centroid_decomposition {
  11.     vector<ll> siz, tree;
  12.     vector<bool> used;
  13.     Centroid_decomposition(ll n) {
  14.         siz.resize(n);
  15.         tree.resize(n);
  16.         used.resize(n);
  17.     }
  18.     void sizes(ll v, ll p) {
  19.         siz[v] = 1;
  20.         for (ll& u : gr[v]) {
  21.             if (u != p && !used[u]) {
  22.                 sizes(u, v);
  23.                 siz[v] += siz[u];
  24.             }
  25.         }
  26.     }
  27.     ll centroid(ll v, ll p, ll s) {
  28.         for (ll& u : gr[v]) {
  29.             if (u != p && !used[u] && siz[u] > s / 2) {
  30.                 return centroid(u, v, s);
  31.             }
  32.         }
  33.         return v;
  34.     }
  35.     void build_centroid(ll v, ll p) {
  36.         sizes(v, -1);
  37.         tree[v] = p;
  38.         used[v] = 1;
  39.         for (ll& u : gr[v]) {
  40.             if (!used[u]) {
  41.                 build_centroid(centroid(u, -1, siz[u]), v);
  42.             }
  43.         }
  44.     }
  45.     void build() {
  46.         sizes(0, -1);
  47.         build_centroid(centroid(0, -1, siz[0]), -1);
  48.     }
  49. };
  50. signed main() {
  51. #ifdef _DEBUG
  52.     freopen("input.txt", "r", stdin);
  53.     freopen("output.txt", "w", stdout);
  54. #endif
  55.     ios_base::sync_with_stdio(false);
  56.     cin.tie(nullptr);
  57.     cout.tie(nullptr);
  58.     ll n;
  59.     cin >> n;
  60.     gr.resize(n);
  61.     for (ll i = 0; i < n - 1; i++) {
  62.         ll u, v;
  63.         cin >> u >> v;
  64.         u--, v--;
  65.         gr[u].push_back(v);
  66.         gr[v].push_back(u);
  67.     }
  68.     Centroid_decomposition U(n);
  69.     U.build();
  70.     for (ll i = 0; i < n; i++) {
  71.         cout << U.tree[i] + 1 << ' ';
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement