# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
53927 | ruhanhabib39 | Network (BOI15_net) | C++17 | 840 ms | 155956 KiB |
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 MAXN = 5e5;
int n;
vector<int> G[MAXN + 10];
vector<pair<int,int>> edges;
bool done[MAXN + 10];
int sz[MAXN + 10];
void dfs1(int u, int p = -1) {
for(int v : G[u]) {
if(v != p) dfs1(v, u);
}
sz[u] = 0;
if((int)G[u].size() == 1) {
sz[u] = 1;
}
for(int v : G[u]) {
if(v != p) sz[u] += sz[v];
}
return;
}
int lc = 0;
int dfs2(int u, int p = -1) {
for(int v : G[u]) {
if(v != p && sz[v] > (lc+1)/2) return dfs2(v, u);
}
return u;
}
int centroid(int u) {
dfs1(u); lc = sz[u];
return dfs2(u);
}
void work() {
int root = 1;
while((int)G[root].size() == 1) ++root;
root = centroid(root);
vector<int> leaves;
for(int v : G[root]) {
function<void(int,int)> dfs = [&](int u, int p) {
if((int)G[u].size() == 1) {
leaves.push_back(u);
}
for(int w : G[u]) {
if(w != p) dfs(w, u);
}
};
dfs(v, root);
}
for(int i = 0; i < lc/2; i++) {
edges.emplace_back(leaves[i], leaves[i + (lc + 1)/2]);
}
if(lc & 1) {
edges.emplace_back(leaves[(lc+1)/2-1], root);
}
}
int main() {
scanf("%d", &n);
for(int i = 1; i < n; i++) {
int u, v; scanf("%d%d", &u, &v);
G[u].push_back(v);
G[v].push_back(u);
}
work();
printf("%d\n", (int)edges.size());
for(auto it : edges) printf("%d %d\n", it.first, it.second);
}
Compilation message (stderr)
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|---|---|---|---|
Fetching results... |