Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #define debug(l) cerr<<#l<<' '<<l<<'\n';
- #include "bits/stdc++.h"
- using namespace std;
- #define all(a) a.begin(), a.end()
- typedef int ll;
- typedef pair<ll, ll> pll;
- typedef long double ld;
- vector<vector<ll>> gr;
- struct Centroid_decomposition {
- vector<ll> siz, tree;
- vector<bool> used;
- Centroid_decomposition(ll n) {
- siz.resize(n);
- tree.resize(n);
- used.resize(n);
- }
- void sizes(ll v, ll p) {
- siz[v] = 1;
- for (ll& u : gr[v]) {
- if (u != p && !used[u]) {
- sizes(u, v);
- siz[v] += siz[u];
- }
- }
- }
- ll centroid(ll v, ll p, ll s) {
- for (ll& u : gr[v]) {
- if (u != p && !used[u] && siz[u] > s / 2) {
- return centroid(u, v, s);
- }
- }
- return v;
- }
- void build_centroid(ll v, ll p) {
- sizes(v, -1);
- tree[v] = p;
- used[v] = 1;
- for (ll& u : gr[v]) {
- if (!used[u]) {
- build_centroid(centroid(u, -1, siz[u]), v);
- }
- }
- }
- void build() {
- sizes(0, -1);
- build_centroid(centroid(0, -1, siz[0]), -1);
- }
- };
- signed main() {
- #ifdef _DEBUG
- freopen("input.txt", "r", stdin);
- freopen("output.txt", "w", stdout);
- #endif
- ios_base::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- ll n;
- cin >> n;
- gr.resize(n);
- for (ll i = 0; i < n - 1; i++) {
- ll u, v;
- cin >> u >> v;
- u--, v--;
- gr[u].push_back(v);
- gr[v].push_back(u);
- }
- Centroid_decomposition U(n);
- U.build();
- for (ll i = 0; i < n; i++) {
- cout << U.tree[i] + 1 << ' ';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement