This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
/*
Code by @marlov
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <utility>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <iterator>
using namespace std;
typedef long long ll;
typedef pair<int,int> pi;
#define maxN 500000
int N;
int root=0;
vector<int> adj[maxN];
vector< pair<int,int> > edges;
queue<int> vals[maxN];
void dfs(int n,int p){
if(adj[n].size()==1){
vals[n].push(n);
return;
}
int lv=n;
for(int i:adj[n]) if(i!=p){
dfs(i,n);
if(vals[i].size()>vals[lv].size()) lv=i;
}
swap(vals[n],vals[lv]);
for(int i:adj[n]) if(i!=p){
while(vals[n].size()>(n==root?0:1)&&vals[i].size()>0){
edges.push_back(make_pair(vals[n].front(),vals[i].front()));
vals[n].pop();
vals[i].pop();
}
while(vals[i].size()>0){
vals[n].push(vals[i].front());
vals[i].pop();
}
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin>>N;
int u,v;
for(int i=0;i<N-1;i++){
cin>>u>>v;
u--;v--;
adj[u].push_back(v);
adj[v].push_back(u);
if(adj[u].size()>adj[root].size()){
root=u;
}
if(adj[v].size()>adj[root].size()){
root=v;
}
}
cout<<root<<endl;
dfs(root,-1);
while(vals[root].size()>1){
int f=vals[root].front();vals[root].pop();
int s=vals[root].front();vals[root].pop();
edges.push_back(make_pair(f,s));
}
if(vals[root].size()==1){
edges.push_back(make_pair(vals[root].front(),root));
}
cout<<edges.size()<<'\n';
for(int i=0;i<edges.size();i++){
cout<<edges[i].first+1<<" "<<edges[i].second+1<<'\n';
}
return 0;
}
/* stuff you should look for
* int overflow, array bounds
* special cases (n=1,n=0?)
* do smth instead of nothing and stay organized
*/
Compilation message (stderr)
net.cpp: In function 'int main()':
net.cpp:85:15: warning: comparison of integer expressions of different signedness: 'int' and 'std::vector<std::pair<int, int> >::size_type' {aka 'long unsigned int'} [-Wsign-compare]
85 | for(int i=0;i<edges.size();i++){
| ~^~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |