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>
#pragma GCC optimize("O3", "unroll-loops")
#define pb emplace_back
#define ins insert
#define ssize(x) (int)x.size()
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pii pair <int, int>
#define pll pair <ll, ll>
#define pld pair <ld, ld>
#define st first
#define nd second
using namespace std;
using ll = int_fast64_t;
// using lll = __int128_t;
using ld = long double;
const int oo = 1e9 + 7;
const int mod = 1e9 + 7;
void solve(){
int n; cin >> n;
vector <int> deg(n, 0);
vector <vector<int>> g(n);
for(int i = 1; i < n; i ++){
int a, b; cin >> a >> b;
-- a; -- b;
g[a].pb(b);
g[b].pb(a);
deg[a] ++;
deg[b] ++;
}
vector <int> dp(n);
int cnt = 0, root;
for(int i = 0; i < n; i ++){
if(deg[i] == 1){
++ cnt;
dp[i] = 1;
}
else root = i;
}
function<void(int, int)> cnt_dp = [&](int v, int p){
for(auto u: g[v]){
cnt_dp(u, v);
dp[v] += dp[u];
}
};
function<int(int, int)> find = [&](int v, int p){
for(auto u: g[v]){
if(deg[u] != 1 && dp[u] > 2 * cnt){
dp[v] -= dp[u];
dp[u] += dp[v];
find(u, p);
}
}
return v;
};
int cent = find(root, -1);
vector <int> leaves;
function<void(int, int)> dfs = [&](int v, int p){
if(deg[v] == 1) leaves.pb(v);
for(auto u: g[v]){
if(u == p) continue;
dfs(u, v);
}
};
dfs(cent, -1);
int k = ssize(leaves);
cout << (k + 1) / 2 << '\n';
for(int i = 0; i < k / 2; i ++) cout << leaves[i] + 1 << ' ' << leaves[i + k / 2] + 1 << '\n';
if(k & 1) cout << leaves[0] + 1 << ' ' << leaves.back() + 1 << '\n';
}
signed main(){
ios_base::sync_with_stdio(0); cin.tie(0);
int t; t = 1;
// cin >> t;
while(t --) solve();
return 0;
}
Compilation message (stderr)
net.cpp: In function 'void solve()':
net.cpp:34:18: warning: 'root' may be used uninitialized in this function [-Wmaybe-uninitialized]
34 | int cnt = 0, root;
| ^~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |