/*
* @author Kian Chua
* @date 01/2025
*
*/
#include <bits/stdc++.h>
#define ll long long
#define pb push_back
#define mp make_pair
#define f first
#define s second
using namespace std;
int n;
vector<vector<int> > connect;
vector<bool> explored;
vector<int> parent;
priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq;
ll swaps_mx = 0;
vector<int> sz;
vector<int> preorder;
// returns depth of node (leaf nodes have depth=0)
int dfs(int i, int p) {
explored[i] = true;
parent[i] = p;
preorder.pb(i);
int sz_i = 1;
int depth = -1;
for (int j : connect[i]) {
if (!explored[j]) {
depth = max(depth, dfs(j, i));
sz_i += sz[j];
}
}
sz[i] = sz_i;
swaps_mx += min(sz_i, n-sz_i);
depth++;
pq.push(mp(depth, i));
return depth;
}
void solve() {
cin >> n;
connect.resize(n);
parent.resize(n);
explored.resize(n, false);
sz.resize(n, 0);
for (int i = 0; i < n-1; i++) {
int a, b; cin >> a >> b; a--; b--;
connect[a].pb(b);
connect[b].pb(a);
}
dfs(0, -1);
vector<int> smallest(n);
for (int i = 0; i < n; i++) { smallest[i] = i+1; }
int swaps = 0;
while (!pq.empty()) {
int cur = pq.top().s; pq.pop();
if (!explored[cur]) { continue; }
if (cur == 0) { // special handling
swaps++;
swap(smallest[cur], smallest[connect[cur][0]]);
continue;
}
explored[cur] = false;
explored[parent[cur]] = false;
// swap with parent
swaps++;
swap(smallest[cur], smallest[parent[cur]]);
}
vector<int> largest(n);
for (int i = 0; i < n; i++) {
largest[preorder[i]] = preorder[(i+(n/2))%n] + 1;
}
cout << 2*swaps << " " << 2*swaps_mx << endl;
for (int i : smallest) { cout << i << " "; } cout << endl;
for (int i : largest) { cout << i << " "; } cout << endl;
return;
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
int t = 1; //cin >> t;
while(t--) { solve(); }
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |