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>
#define ll long long
#define lsb(x) (x & -x)
using namespace std;
void dfs(int node, int dad, const vector<vector<int>> &g, vector<int> &leaves) {
bool flag = 0;
for(auto it : g[node]) {
if(it != dad) {
dfs(it, node, g, leaves);
leaves[node] += leaves[it];
flag = 1;
}
}
if(!flag)
leaves[node] = 1;
}
void getleaves(int node, int dad, const vector<vector<int>> &g, vector<int> &v) {
bool flag = 0;
for(auto it : g[node]) {
if(it == dad)
continue;
getleaves(it, node, g, v);
flag = 1;
}
if(!flag)
v.push_back(node);
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//freopen("a.in", "r", stdin);
//freopen("a.out", "w", stdout);
int n;
cin >> n;
vector<vector<int>> g(n + 1);
int start = 1;
for(int i = 1; i < n; i ++) {
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
}
for(int i = 1; i <= n; i ++)
if(g[i].size() > 1)
start = i;
vector<int> leaves(n + 1, 0);
dfs(start, 0, g, leaves);
int centroid = 0;
for(int i = 1; i <= n; i ++) {
int lim = leaves[start] / 2;
bool isok = 1;
for(auto it : g[i]) {
if(leaves[it] > leaves[i] && leaves[it] - leaves[i] > lim)
isok = 0;
if(leaves[it] <= leaves[i] && leaves[it] > lim)
isok = 0;
}
if(isok && g[i].size() > 1) /// a doua conditie de aici???
centroid = i;
}
//assert(centroid != 0);
priority_queue<pair<int, int>> pq;
vector<vector<int>> listofleaves(n + 1);
for(auto it : g[centroid]) {
getleaves(it, centroid, g, listofleaves[it]);
pq.push({listofleaves[it].size(), it});
}
vector<pair<int, int>> sol;
while(pq.size() >= 2) {
auto a = pq.top().second;
pq.pop();
auto b = pq.top().second;
pq.pop();
sol.push_back({listofleaves[a].back(), listofleaves[b].back()}); /// to change
listofleaves[a].pop_back();
listofleaves[b].pop_back();
if(listofleaves[a].size() > 0)
pq.push({listofleaves[a].size(), a});
if(listofleaves[b].size() > 0)
pq.push({listofleaves[b].size(), b});
}
if(pq.size() == 1)
sol.push_back({centroid, listofleaves[pq.top().second].back()});
cout << sol.size() << "\n";
for(auto it : sol)
cout << it.first << " " << it.second << "\n";
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... |