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 fi first
#define se second
#define sz(x) (int)x.size()
#define ALL(v) v.begin(),v.end()
#define MASK(k) (1LL << (k))
#define BIT(x, i) (((x) >> (i)) & 1)
#define oo (ll)1e18
#define INF (ll)1e9
#define MOD (ll)(1e9 + 7)
using namespace std;
template<class T1, class T2>
bool maximize(T1 &a, T2 b){if(a < b){a = b; return true;} return false;}
template<class T1, class T2>
bool minimize(T1 &a, T2 b){if(a > b){a = b; return true;} return false;}
template<class T1, class T2>
void add(T1 &a, T2 b){a += b; if(a >= MOD) a -= MOD;}
template<class T1, class T2>
void sub(T1 &a, T2 b){a -= b; if(a < 0) a += MOD;}
template<class T>
void cps(T &v){sort(ALL(v)); v.resize(unique(ALL(v)) - v.begin());}
const int MAX = 5e5 + 10;
int N;
vector<int> adj[MAX];
vector<int> leaves;
void dfs(int u, int p = -1){
if(sz(adj[u]) == 1) leaves.push_back(u);
for(int v: adj[u]){
if(v == p) continue;
dfs(v, u);
}
}
void solve(){
cin >> N;
for(int i = 1; i < N; i++){
int u, v; cin >> u >> v;
adj[u].push_back(v);
adj[v].push_back(u);
}
clock_t start = clock();
if(N == 2){
cout << 1 << '\n' << "1 2\n";
return;
}
int root;
for(int i = 1; i <= N; i++){
if(sz(adj[i]) > 1){
root = i;
break;
}
}
dfs(root);
vector<pair<int, int>> ans;
int n = sz(leaves);
for(int i = 0; i < n / 2; i++){
ans.push_back({leaves[i], leaves[i + n / 2]});
}
if(sz(leaves) & 1){
ans.push_back({leaves[0], leaves.back()});
}
cout << sz(ans) << '\n';
for(auto o: ans){
cout << o.fi << ' ' << o.se << '\n';
}
cerr << "Time elapsed: " << clock() - start << " ms\n";
}
int main(){
ios_base::sync_with_stdio(0); cin.tie(0);
// freopen("walk.inp","r",stdin);
// freopen("walk.out","w",stdout);
int t = 1;
// cin >> t;
while(t--)
solve();
return 0;
}
Compilation message (stderr)
net.cpp: In function 'void solve()':
net.cpp:67:8: warning: 'root' may be used uninitialized in this function [-Wmaybe-uninitialized]
67 | dfs(root);
| ~~~^~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |