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;
typedef long long int ll;
typedef long double ld;
#define f first
#define s second
#define pb push_back
const int N = 5e5 + 100;
const ld inf = 1e8;
const ll mod = 1e9 + 7;
int r, par[N], sz[N], d[N];
vector<int> adj[N], l[N];
vector<pair<int, int>> ans;
set<pair<int, int>> st;
void dfs(int u)
{
sz[u] = 0;
for(auto x : adj[u])
{
if(x == par[u])
continue;
par[x] = u;
dfs(x);
sz[u] += sz[x];
}
if(int(adj[u].size()) == 1)
sz[u] = 1;
}
int find(int u)
{
//cout << u + 1 << endl;
for(auto x : adj[u])
{
if(x != par[u] && sz[x] > sz[r]/2)
return find(x);
}
return u;
}
void DFS(int u)
{
for(auto x : adj[u])
{
if(x != par[u])
{
par[x] = u;
DFS(x);
}
}
if(adj[u].size() == 1)
l[r].pb(u);
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int n;
cin >> n;
for(int i = 0; i < n - 1; i++)
{
int x, y;
cin >> x >> y;
x--; y--;
adj[x].pb(y);
adj[y].pb(x);
}
for(int i = 0; i < n; i++)
{
if(int(adj[i].size()) > 1)
{
r = i;
break;
}
}
par[r] = r;
dfs(r);
//cout << "///////////////////////" << endl;
//for(int i = 0; i < n; i++)
//cout << i + 1 << ' ' << sz[i] << ' ' << par[i] + 1 << ' ' << adj[i].size() << endl;
int u = find(r);
//cout << u << endl;
par[u] = u;
for(auto x : adj[u])
{
par[x] = u;
r = x;
DFS(x);
d[x] = l[x].size();
st.insert({-d[x], x});
}
while(st.size() >= 2)
{
int x = st.begin()->s;
st.erase(st.begin());
int y = st.begin()->s;
st.erase(st.begin());
d[x]--; d[y]--;
ans.pb({l[x][d[x]], l[y][d[y]]});
if(d[x])
st.insert({-d[x], x});
if(d[y])
st.insert({-d[y], y});
}
if(st.size())
{
int x = st.begin() -> s;
d[x]--;
ans.pb({u, l[x][d[x]]});
}
cout << ans.size() << endl;
for(auto it : ans)
cout << it.f + 1 << ' ' << it.s + 1 << endl;
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... |