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;
vector <vector <int>> ad;
vector <int> sub;
vector <bool> viz;
int nrf, cf;
void dfs(int nod){
viz[nod] = true;
if(ad[nod].size() == 1){
sub[nod] = 1;
return;
}
for(auto fiu : ad[nod])
if(!viz[fiu]){
dfs(fiu);
sub[nod] += sub[fiu];
}
}
int get_centroid(int nod){
for(auto fiu : ad[nod])
if(sub[fiu] > nrf / 2)
return get_centroid(fiu);
return nod;
}
bool cmp(const vector <int> &a, const vector <int> &b){
return a.size() > b.size();
}
void Frunza(int nod, vector <int> &v){
viz[nod] = true;
if(ad[nod].size() == 1){
v.push_back(nod);
return;
}
for(auto fiu : ad[nod])
if(!viz[fiu])
Frunza(fiu, v);
}
int main()
{
int n, x, y;
cin >> n;
nrf = n;
ad.resize(n + 1);
sub.resize(n + 1);
for(int i = 1; i < n; i++){
cin >> x >> y;
ad[x].push_back(y);
ad[y].push_back(x);
}
viz.resize(n + 1);
dfs(1);
nrf = sub[1];
cf = get_centroid(1);
fill(viz.begin(), viz.end(), false);
viz[cf] = true;
vector <vector <int>> gramezi;
for(auto fiu : ad[cf]){
vector <int> v;
gramezi.push_back(v);
Frunza(fiu, gramezi.back());
}
cout << (nrf + 1) / 2 << '\n';
if(nrf % 2 == 1){
cout << cf << ' ' << gramezi[0].back() << '\n';
gramezi[0].pop_back();
sort(gramezi.begin(), gramezi.end(), cmp);
}
while(gramezi[0].size() > 0){
cout << gramezi[0].back() << ' ' << gramezi[1].back() << '\n';
gramezi[0].pop_back();
gramezi[1].pop_back();
sort(gramezi.begin(), gramezi.end(), cmp);
}
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |