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 IO ios::sync_with_stdio(false);cin.tie(0);
#define debug(x) cerr << #x << " = " << (x) << ' '
#define bug(x) cerr << (x) << ' '
#define endl cerr << '\n'
#define all(v) (v).begin(), (v).end()
#define SZ(v) (ll)(v).size()
#define lowbit(x) (x)&-(x)
#define pb emplace_back
#define F first
#define S second
using namespace std;
using ll = long long;
using pll = pair<ll, ll>;
const int N = 5e5+5;
int n, dis[N], fa[N], dsu[N];
pll e[N];
vector<int> g[N];
vector<pll> v2;
inline int query(int x) { return (dsu[x]<0)?x : dsu[x]=query(dsu[x]); }
inline bool unite(int x, int y)
{
x = query(x), y = query(y); if (x == y) return 0;
if (-dsu[x] < -dsu[y]) swap(x, y);
dsu[x] += dsu[y], dsu[y] = x; return 1;
}
inline void dfs(int x, int pre)
{
dis[x] = dis[pre] + 1, fa[x] = pre;
for (int v : g[x]) if (v != pre) dfs(v, x);
}
inline pll find_dis()
{
int pos = query(1), pos2;
dfs(pos, 0);
for (int i=1; i <= n; ++i)
if (dsu[i] == -1 && dis[i] > dis[pos]) pos = i;
dfs(pos, 0), pos2 = pos;
for (int i=1; i <= n; ++i)
if (dsu[i] == -1 && dis[i] > dis[pos2]) pos2 = i;
return {pos, pos2};
}
int main(void)
{ IO
int i, x, y;
cin >> n;
for (i=1; i <= n-1; ++i) cin >> x >> y, e[i] = {x, y};
int cnt = n, t=0;
for (i=1; i <= n; ++i) dsu[i] = -1;
while (cnt > 1 && t < 100)
{
//debug(cnt), endl;
for (i=1; i <= n; ++i) g[i].clear();
for (i=1; i <= n-1; ++i)
{
x = query(e[i].F), y = query(e[i].S);
//if (x != y) debug(x), debug(y), endl;
if (x != y) g[x].pb(y), g[y].pb(x);
}
for (i=1; i <= n; ++i)
{
if (SZ(g[i]) == cnt-1)
{
for (int j=1; j < SZ(g[i]); j+=2) v2.pb(g[i][j-1], g[i][j]);
if (SZ(g[i]) & 1) v2.pb(i, g[i].back());
cnt = 1;
break;
}
}
if (i <= n) break;
auto tp = find_dis();
v2.pb(tp.F, tp.S);
int cur = tp.S;
do {
if (fa[cur]) cnt -= unite(cur, fa[cur]);
cur = fa[cur];
} while (cur);
//debug(dis[tp.S]-1), debug(cnt), endl;
//for (i=1; i <= n; ++i) bug(query(i)); endl;
++t;
}
if (cnt != 1) assert(0);
cout << SZ(v2) << '\n';
for (auto p : v2) cout << p.F << ' ' << p.S << '\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... |