1+ /* *
2+ * @file 2108E.cpp
3+ * @author Macesuted (i@macesuted.moe)
4+ * @date 2025-05-07
5+ *
6+ * @copyright Copyright (c) 2025
7+ *
8+ */
9+
10+ #include < bits/stdc++.h>
11+ using namespace std ;
12+
13+ #ifndef LOCAL
14+ #define endl ' \n '
15+ #endif
16+
17+ bool mem1;
18+
19+ #define maxn 200005
20+
21+ using pii = pair<int , int >;
22+
23+ vector<vector<int >> graph;
24+ int col[maxn], fa[maxn], dep[maxn], siz[maxn], dfn[maxn], id[maxn];
25+ int n;
26+
27+ int dfnt;
28+ void dfs (int p) {
29+ id[dfn[p] = ++dfnt] = p, siz[p] = 1 ;
30+ for (auto q : graph[p]) {
31+ if (q == fa[p]) continue ;
32+ fa[q] = p, dep[q] = dep[p] + 1 ;
33+ dfs (q);
34+ siz[p] += siz[q];
35+ }
36+ return ;
37+ }
38+ int getRoot (int p) {
39+ for (auto q : graph[p])
40+ if (q != fa[p] && 2 * siz[q] > n) return getRoot (q);
41+ return p;
42+ }
43+
44+ void solve (void ) {
45+ cin >> n;
46+
47+ graph.clear (), graph.resize (n + 1 );
48+ for (int i = 1 , x, y; i < n; i++) cin >> x >> y, graph[x].push_back (y), graph[y].push_back (x);
49+
50+ fa[1 ] = -1 , dep[1 ] = 0 , dfnt = 0 , dfs (1 );
51+ int root = getRoot (1 );
52+ fa[root] = -1 , dep[root] = 0 , dfnt = 0 , dfs (root);
53+
54+ int x = -1 ;
55+ for (int i = 1 ; i <= n; i++)
56+ if (i != root && (x == -1 || siz[i] + dep[i] < siz[x] + dep[x])) x = i;
57+
58+ cout << x << ' ' << fa[x] << endl;
59+
60+ for (int i = 1 ; i <= n; i++) col[i] = 0 ;
61+ vector<int > nodes;
62+ for (int i = 1 ; i <= n; i++)
63+ if (id[i] != x) nodes.push_back (id[i]);
64+ for (int i = 0 , j = nodes.size () / 2 ; j < (int )nodes.size (); i++, j++) col[nodes[i]] = col[nodes[j]] = i + 1 ;
65+ if (x < fa[x]) swap (col[x], col[fa[x]]);
66+
67+ for (int i = 1 ; i <= n; i++) cout << col[i] << ' ' ;
68+ cout << endl;
69+
70+ return ;
71+ }
72+
73+ bool mem2;
74+
75+ int main () {
76+ ios::sync_with_stdio (false ), cin.tie (nullptr );
77+ #ifdef LOCAL
78+ cerr << " Memory Cost: " << abs (&mem1 - &mem2) / 1024 . / 1024 . << " MB" << endl;
79+ #endif
80+
81+ int _ = 1 ;
82+ cin >> _;
83+ while (_--) solve ();
84+
85+ #ifdef LOCAL
86+ cerr << " Time Cost: " << clock () * 1000 . / CLOCKS_PER_SEC << " MS" << endl;
87+ #endif
88+ return 0 ;
89+ }
0 commit comments