This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include "bits/stdc++.h"
using namespace std;
vector<vector<int>> graph;
vector<int> leaves_from, leaves, res;
int leaf_count, res_count;
void count_leaves(int node, int parent) {
if (graph[node].size() == 1)
leaves_from[node] = 1;
for (auto adj : graph[node]) {
if (adj == parent)
continue;
count_leaves(adj, node);
leaves_from[node] += leaves_from[adj];
}
}
int find_mid(int node) {
int parent = 0;
for (auto adj : graph[node])
if (adj != parent && leaves_from[adj] > leaf_count / 2) {
parent = node;
node = adj;
}
return node;
}
void add_leaves(int node, int parent) {
if (graph[node].size() == 1)
leaves.push_back(node);
for (auto adj : graph[node])
if (adj != parent)
add_leaves(adj, node);
}
int split(int n) {
count_leaves(1, 0);
int mid = find_mid(1);
for (auto adj : graph[mid])
add_leaves(adj, mid);
return mid;
}
void run() {
int n;
cin >> n;
if (n == 1) {
cout << 0;
return;
}
if (n == 2) {
cout << "1\n2";
return;
}
graph = vector<vector<int>>(n + 1);
leaves_from = vector<int>(n + 1);
for (int i = 0; i < n - 1; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
graph[b].push_back(a);
}
for (int i = 1; i <= n; i++)
if (graph[i].size() == 1)
leaf_count++;
res_count = (leaf_count + 1) / 2;
cout << res_count;
leaves.reserve(2 * res_count);
res.resize(2 * res_count);
split(n);
int i = 0;
for (auto leaf : leaves) {
res[i] = leaf;
i += 2;
if (i == res_count * 2)
i = 1;
}
if (!res.empty() && res.back() == 0)
res.back() = leaves[0];
for (int i = 0; i < res_count; i++)
cout << '\n' << res[2 * i] << ' ' << res[2 * i + 1];
}
auto main() -> int {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
run();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |