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;
const int maxn = 5e5 + 10;
vector < int > g[maxn] , leaf;
int cnt[maxn] , par[maxn];
void DFS(int u,int p) {
if (g[u].size() == 1) leaf.push_back(u);
for (auto v : g[u])
if (v != p) {
par[v] = u;
DFS(v , u);
}
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
int n , root;
cin >> n;
for (int i = 1 ; i < n ; ++i) {
int u , v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
if (g[u].size() > 1) root = u;
if (g[v].size() > 1) root = v;
}
DFS(root , 0);
int half = leaf.size() / 2;
cout << (leaf.size() + 1) / 2 << '\n';
if ((leaf.size()) % 2 == 0) {
for (int j = 0 ; j < half ; ++j)
cout << leaf[j] << ' ' << leaf[half + j] << '\n';
} else {
int ma = 0;
for (auto v : leaf) {
cnt[par[v]]++;
ma = max(ma , cnt[par[v]]);
}
int pos;
for (int i = 0 ; i < leaf.size() ; ++i)
if (cnt[par[leaf[i]]] == ma) {
cout << leaf[i] << ' ' << root << '\n';
pos = i;
break;
}
leaf.erase(leaf.begin() + pos);
for (int j = 0 ; j < half ; ++j)
cout << leaf[j] << ' ' << leaf[half + j] << '\n';
}
}
Compilation message (stderr)
net.cpp: In function 'int main()':
net.cpp:45:28: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
45 | for (int i = 0 ; i < leaf.size() ; ++i)
| ~~^~~~~~~~~~~~~
net.cpp:47:47: warning: 'root' may be used uninitialized in this function [-Wmaybe-uninitialized]
47 | cout << leaf[i] << ' ' << root << '\n';
| ^~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |