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 = 500001;
bool visited[N];
int LeavesInsubtee[N];
vector<int> adj[N];
vector<int> res[N];
int n;
int ans = 0;
int subtreeValue = 0;
void dfs(int u){
visited[u] = true;
if((int)adj[u].size() == 1){
LeavesInsubtee[u] = 1;
}
for(int v : adj[u]){
if(!visited[v]){
dfs(v);
LeavesInsubtee[u] += LeavesInsubtee[v];
}
}
}
void dfs2(int u){
visited[u] = true;
if((int)adj[u].size() == 1){
res[subtreeValue].push_back(u);
}
for(int v : adj[u]){
if(!visited[v]){
dfs2(v);
}
}
}
int cutlocation(int u){
visited[u] = true;
for(int v : adj[u]){
if(!visited[v]){
if(LeavesInsubtee[v] > floor(ans/2)){
return cutlocation(v);
}
}
}
return u;
}
int cut(int u){
dfs(1);
for(int i = 1; i <= n; i++){
visited[i] = false;
}
int x = cutlocation(1);
for(int i = 1; i <= n; i++){
visited[i] = false;
}
visited[x] = true;
for(int v : adj[x]){
subtreeValue++;
dfs2(v);
}
return x;
}
int main(){
cin >> n;
for(int i = 0; i < n - 1; i++){
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
for(int i = 1; i <= n; i++){
if((int)adj[i].size() == 1){
ans++;
}
}
ans = (ans + 1)/2;
cout << ans << "\n";
cut(n);
vector<int> finalAns(2 * ans);
int idx = 0;
for(int i = 1; i <= subtreeValue; i++){
for(int j = 0; j < (int)res[i].size(); j++){
finalAns[idx] = res[i][j];
idx += 2;
if(idx == 2 * ans){
idx = 1;
}
}
}
if(!(finalAns.empty()) && finalAns.back() == 0){
finalAns.back() = res[1][0];
}
for(int i = 0; i < (int)finalAns.size(); i += 2){
cout << finalAns[i] << " " << finalAns[i + 1] << "\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... |