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;
const int N=5e5+5;
int n;
int sz[N];
vector<int> adj[N];
int dfssz(int u,int p=0){
sz[u]=(adj[u].size()<2);
for(auto v:adj[u])if(v!=p)sz[u]+=dfssz(v,u);
return sz[u];
}
int centroid(int u,int cnt,int p=0){
for(auto v:adj[u])if(v!=p&&sz[v]>cnt/2)return centroid(v,cnt,u);
return u;
}
void dfs(int u,int p,vector<int> &comp){
if(adj[u].size()==1)comp.emplace_back(u);
for(auto v:adj[u])if(v!=p)dfs(v,u,comp);
}
int main(){
cin.tie(nullptr)->sync_with_stdio(false);
cin >> n;
for(int i=1;i<n;i++){
int u,v;
cin >> u >> v;
adj[u].emplace_back(v);
adj[v].emplace_back(u);
}
int c=1;
for(int i=1;i<=n;i++)if(adj[i].size()>1)c=i;
c=centroid(c,dfssz(c));
vector<vector<int>> res;
int cnt=0;
for(auto v:adj[c]){
res.push_back({});
dfs(v,c,res.back());
cnt+=res.back().size();
}
int m=res.size();
priority_queue<pair<int,int>> pq;
for(int i=0;i<m;i++){
pq.emplace(res[i].size(),i);
assert(res[i].size()<=cnt/2);
}
vector<pair<int,int>> ans;
while(!pq.empty()){
auto [s,i]=pq.top();
pq.pop();
if(pq.empty()){
assert(s==1);
ans.emplace_back(res[i].back(),c);
break;
}
auto [t,j]=pq.top();
pq.pop();
ans.emplace_back(res[i].back(),res[j].back());
res[i].pop_back();
res[j].pop_back();
if(--s)pq.emplace(s,i);
if(--t)pq.emplace(t,j);
}
cout << ans.size() << "\n";
for(auto [x,y]:ans)cout << x << " " << y << "\n";
}
Compilation message (stderr)
In file included from /usr/include/c++/10/cassert:44,
from /usr/include/x86_64-linux-gnu/c++/10/bits/stdc++.h:33,
from net.cpp:1:
net.cpp: In function 'int main()':
net.cpp:50:29: warning: comparison of integer expressions of different signedness: 'std::vector<int>::size_type' {aka 'long unsigned int'} and 'int' [-Wsign-compare]
50 | assert(res[i].size()<=cnt/2);
| ~~~~~~~~~~~~~^~~~~~~
net.cpp:54:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
54 | auto [s,i]=pq.top();
| ^
net.cpp:61:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
61 | auto [t,j]=pq.top();
| ^
net.cpp:70:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
70 | for(auto [x,y]:ans)cout << x << " " << y << "\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... |