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>
#include<unordered_map>
using namespace std;
typedef long long ll;
const ll inf=(1ll<<60);
const ll mod=1e9+7;
const int MX=6e5+9;
int n,m,subtree[MX],par[MX],leaf[MX];
vector<int>v[MX],v1[MX];
void dfs_size(int x,int p){
subtree[x]=1;par[x]=p;
for(auto pp:v[x]){
if(pp==p)continue;
dfs_size(pp,x);
subtree[x]+=subtree[pp];
}
}
int centroid(int x){
dfs_size(x,-1);
int S=subtree[x],idx;
queue<int>q;
q.push(x);
while(!q.empty()){
int nxt=q.front();q.pop();
int s=subtree[x]-subtree[nxt];
for(auto pp:v[nxt]){
if(pp==par[nxt])continue;
s=max(s,subtree[pp]);
q.push(pp);
}
if(S>s){
S=s;
idx=nxt;
}
}
return idx;
}
int x,y,cen,timer;
void dfs(int x,int p){
if(leaf[x]){
v1[timer].push_back(x);
return;
}
for(auto pp:v[x]){
if(pp==p)continue;
dfs(pp,x);
if(x==cen)timer++;
}
}
int leaves;
int cel(int x,int y){
if(x%y==0)return x/y;
return x/y+1;
}
int main(){
scanf("%d",&n);
if(n==1){
puts("0");
return 0;
}
if(n==2){
puts("1");
cout<<1<<" "<<2<<endl;
return 0;
}
for(int i=0;i<n-1;i++){
scanf("%d%d",&x,&y);
v[x].push_back(y);
v[y].push_back(x);
}
for(int i=1;i<=n;i++){
if(v[i].size()==1){
leaf[i]=1;
leaves++;
}
}
int idx=1;
for(int i=1;i<=n;i++)if(!leaf[i])idx=i;
cen=centroid(idx);
dfs(cen,-1);
priority_queue<pair<int,int> >pq;
for(int i=0;i<timer;i++){
pq.push({v1[i].size(),i});
}
printf("%d\n",cel(leaves,2));
while(pq.size()>1){
int com1=pq.top().second,sz1=pq.top().first;pq.pop();
int com2=pq.top().second,sz2=pq.top().first;pq.pop();
printf("%d %d\n",v1[com1][sz1-1],v1[com2][sz2-1]);
--sz1;--sz2;
if(sz1>0)pq.push({sz1,com1});
if(sz2>0)pq.push({sz2,com2});
}
if(!pq.empty()){
printf("%d %d\n",v1[pq.top().second][0],cen);
}
}
Compilation message (stderr)
net.cpp: In function 'int main()':
net.cpp:56:19: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d",&n);
^
net.cpp:67:28: warning: ignoring return value of 'int scanf(const char*, ...)', declared with attribute warn_unused_result [-Wunused-result]
scanf("%d%d",&x,&y);
^
net.cpp: In function 'int centroid(int)':
net.cpp:36:12: warning: 'idx' may be used uninitialized in this function [-Wmaybe-uninitialized]
return idx;
^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |