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;
#define pb push_back
#define fi first
#define se second
typedef pair<int, int> ii;
const int N = 5e5 + 5;
int n, child[N], nLeaf, cur, tmp;
vector<int> gr[N];
set<ii> ver;
void prep (int u, int prev) {
for (int v : gr[u]) if (v != prev) {
prep(v, u);
child[u] += child[v];
}
child[u] += (gr[u].size() == 1);
}
int findCentroid (int u, int prev) {
for (int v : gr[u]) if (v != prev) {
if (child[v] >= (nLeaf + 1) / 2 ) return findCentroid(v, u);
}
return u;
}
void dfs (int u, int prev) {
for (int v : gr[u]) if (v != prev) dfs(v, u);
if (gr[u].size() == 1) ver.insert(ii(cur, u) );
}
int main () {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
for (int _ = 1; _ < n; ++_) {
int u, v; cin >> u >> v;
gr[u].pb(v); gr[v].pb(u);
}
for (int u = 1; u <= n; ++u) nLeaf += (gr[u].size() == 1);
prep(1, 1);
int cen = findCentroid(1, 1);
for (int u : gr[cen]) cur ++, dfs(u, cen);
cout << (nLeaf + 1) / 2 << '\n';
while (ver.size() > 1) {
tmp = (*ver.begin() ).se;
cout << (*ver.begin() ).se << ' ' << (*ver.rbegin() ).se << '\n';
ver.erase(ver.begin() );
set<ii>::iterator it = ver.end(); it --;
ver.erase(it);
}
if (ver.size() ) {
for (int u = 1; u <= n; ++u) if (gr[u].size() == 1 && u != (*ver.begin() ).se) tmp = u;
cout << tmp << ' ' << (*ver.begin() ).se << '\n';
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |