#include <bits/stdc++.h>
#define int long long
using namespace std;
vector<vector<int>> adj, divi;
int n;
void dfs(int x, int pre, int dv) {
for (int y : adj[x]) {
if (x == y) continue;
dfs(y, x, dv);
}
if (adj[x].empty()) divi[dv].push_back(x);
}
signed main() {
cin >> n;
adj.resize(n);
for (int i = 0; i < n -1; i++) {
int a, b; cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
int root = -1;
for (int i = 0; i < n; i++) if (adj[i].size() > 1) root = i;
divi.resize(adj[root].size());
for (int i = 0; i < adj[root].size(); i++) dfs(adj[root][i], root, i);
vector<pair<int,int>> res;
for (int i = 0; i < divi.size(); i++) {
if (i == divi.size() - 1) {
for (int j = 0; j < divi[i].size(); j++) res.push_back({divi[i][j], root});
}
for (int j = 0; j < divi[i].size(); j++) {
res.push_back({divi[i][j], divi.back().back()});
divi.back().pop_back();
if (divi.back().empty()) {
divi.pop_back();
if (i == divi.size() - 1) break;
}
}
}
cout << res.size() << '\n';
for (auto x : res) cout << x.first << ' ' << x.second;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |