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 dis[N];
vector<int> g[N], vec;
vector<pll> v2;
inline void dfs(int x, int pre)
{
dis[x] = dis[pre] + 1;
for (int v : g[x]) if (v != pre) dfs(v, x);
}
inline bool cmp(int x, int y) { return dis[x] < dis[y]; }
int main(void)
{ IO
int n, i, pos;
cin >> n;
for (i=0; i < n-1; ++i)
{
int x, y; cin >> x >> y;
g[x].pb(y), g[y].pb(x);
}
for (i=1; i <= n; ++i) if (SZ(g[i]) == 1) vec.pb(i);
dfs(1, 0);
for (i=2, pos=1; i <= n; ++i) if (dis[i] > dis[pos]) pos = i;
dfs(pos, 0);
for (i=2, pos=1; i <= n; ++i) if (dis[i] > dis[pos]) pos = i;
dfs(pos, 0);
sort(all(vec), cmp);
v2.pb(vec[0], vec.back());
for (int i=2; i < SZ(vec)-1; i+=2) v2.pb(vec[i-1], vec[i]);
if (SZ(vec)&1) v2.pb(vec[SZ(vec)-2], vec.back());
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... |