이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define fr(i, n, m) for(int i = (n); i < (m); i ++)
#define pb push_back
#define st first
#define nd second
#define pq priority_queue
#define all(x) begin(x), end(x)
#include <time.h>
#include <cmath>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
const int i_inf = 1e9;
const ll inf = 1e18;
const ll mod = 1000000007;
const ld eps = 1e-13;
const ld pi = 3.14159265359;
mt19937 _rand(time(NULL));
clock_t timer = clock();
const int mxn = 5e5;
int n;
vector<int> g[mxn];
vector<int> v;
int sz[mxn];
void dfs(int u, int p){
sz[u] = 0;
for(auto e : g[u]){
if(e == p) continue;
dfs(e, u);
sz[u] += sz[e];
}
if((int)g[u].size()==1) ++sz[u];
}
int tot = 0;
int dfs1(int u, int p){
for(auto e : g[u]){
if(e!=p && sz[e] > tot/2) return dfs1(e, u);
}
return u;
}
vector<int> V;
void dfs2(int u, int p){
for(auto e : g[u]){
if(e == p) continue;
dfs2(e, u);
}
if((int)g[u].size()==1) V.pb(u);
}
void solve(){
cin >> n;
fr(i, 0, n-1){
int u, v;
cin >> u >> v;
--u, --v;
g[u].pb(v);
g[v].pb(u);
}
dfs(0, 0);
tot = sz[0];
int leaf_cen = dfs1(0, 0);
pq<pair<int,int> > Q;
vector<vector<int> > v;
for(auto e : g[leaf_cen]){
V.clear();
dfs2(e, leaf_cen);
Q.push({V.size(), v.size()});
v.pb(V);
}
vector<pii> sol;
while(!Q.empty()){
while(!Q.empty() && (int)v[Q.top().nd].size() != (int)Q.top().st){
Q.pop();
}
if(Q.empty())break;
int i = Q.top().nd;
Q.pop();
while(!Q.empty() && (int)v[Q.top().nd].size() != (int)Q.top().st){
Q.pop();
}
if(Q.empty())break;
int j = Q.top().nd;
Q.pop();
int a = v[i].back();
int b = v[j].back();
sol.pb({a, b});
v[i].pop_back();
v[j].pop_back();
if(v[i].size() > 0){
Q.push({v[i].size(), i});
}
if(v[j].size() > 0){
Q.push({v[j].size(), j});
}
}
for(auto u : v){
if(!u.empty()){
sol.pb({u[0], leaf_cen});
}
}
cout<<sol.size() << endl;
for(auto u : sol){
cout<<u.st+1<<' '<<u.nd+1<<endl;
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |