이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define int long long
#define pb push_back
using namespace std;
const int maxn = 5e5+10;
const int inf = 1e18;
const int mod = 1e9+7;
int n,cnt,root(-1);
int pendant[2][maxn],deg[maxn]; // 0 -> max , 1 -> sum
vector<int>G[maxn];
vector<int>ans;
void dfs(int v,int par){
for(int b : G[v]){
if(b == par) continue;
dfs(b,v);
pendant[1][v] += pendant[1][b];
pendant[0][v] = max(pendant[0][v],pendant[1][b]);
}
if(deg[v] == 1){
pendant[1][v]++;
}
pendant[0][v] = max(pendant[0][v],cnt-pendant[1][v]);
if(pendant[0][v] <= cnt/2 && root == -1 && deg[v] != 1)
root = v;
}
void dfss(int v,int par){
if(deg[v] == 1)
ans.pb(v);
for(int b : G[v]){
if(b == par) continue;
dfss(b,v);
}
}
int32_t main(){
ios:: sync_with_stdio(0),cin.tie(0),cout.tie(0);
////////////////////////////////////////////////
cin >> n;
for(int i = 1;i<n;i++){
int a,b; cin >> a >> b;
G[a].pb(b),G[b].pb(a);
deg[a]++,deg[b]++;
}
for(int i = 1;i<=n;i++){
if(deg[i] == 1){
cnt++;
}
}
dfs(1,-1);
dfss(root,-1);
int sz = ans.size();
if(sz&1){
cout << (sz+1)/2 << "\n";
int len = (sz+1)/2;
for(int i = 0;i<(sz+1)/2;i++){
cout << ans[i] << " " << ans[min(i+len,sz-1)] << "\n";
}
}
else{
cout << sz/2 << "\n";
int len = sz/2;
for(int i = 0;i<sz/2;i++){
cout << ans[i] << " " << ans[i+len] << "\n";
}
}
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |