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>
#define F first
#define S second
#define pb push_back
using namespace std;
const int N = 2000 + 10, LG = 20;
int n, h[N], par[N][LG];
bool mark[N];
vector<int> G[N], vec;
vector<pair<int, pair<int, int>>> vec1;
void dfs(int v = 1, int p = 0) {
for (int lg = 1; lg < LG; lg++)
par[v][lg] = par[par[v][lg - 1]][lg - 1];
if (G[v].size() == 1) vec.pb(v);
for (auto e : G[v])
if (e ^ p) {
h[e] = h[v] + 1, par[e][0] = v;
dfs(e, v);
}
}
int lca(int u, int v) {
if (u == v) return u;
if (h[u] < h[v]) swap(u, v);
int k = h[u] - h[v];
for (int lg = 0; lg < LG; lg++)
if (k & (1 << lg)) u = par[u][lg];
if (u == v) return v;
for (int lg = LG - 1; lg >= 0; lg--)
if (par[u][lg] != par[v][lg]) u = par[u][lg], v = par[v][lg];
return par[u][0];
}
int main() {
ios:: sync_with_stdio(0), cin.tie(0);
cin >> n;
for (int i = 0; i < n - 1; i++) {
int u, v;
cin >> u >> v;
G[u].pb(v);
G[v].pb(u);
}
dfs();
for (int i = 0; i < (int)vec.size(); i++)
for (int j = i + 1; j < (int)vec.size(); j++) {
int l = lca(vec[i], vec[j]);
vec1.pb({h[vec[i]] + h[vec[j]] - 2 * h[l], {vec[i], vec[j]}});
}
sort(vec1.begin(), vec1.end());
reverse(vec1.begin(), vec1.end());
cout << ((int)vec.size() + 1) / 2 << endl;
for (auto e : vec1) {
int cnt = 0;
for (int i = 1; i <= n; i++)
if (mark[i]) cnt++;
if (cnt == (int) vec.size()) return 0;
if (!mark[e.S.F] && !mark[e.S.S]) {
cout << e.S.F << ' ' << e.S.S << endl;
mark[e.S.F] = mark[e.S.S] = true;
}
else if ((int)vec.size() & 1)
if (cnt + 1 == (int)vec.size()) {
if (!mark[e.S.S]) return cout << vec1[0].S.F << ' ' << e.S.S << endl, 0;
else if (!mark[e.S.F]) return cout << vec1[0].S.F << ' ' << e.S.F << endl, 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... |