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;
#define lesgooo ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define endl '\n'
#define int long long
const int N = 5e5+5;
vector<int> adj[N], leaf;
void dfs(int i, int par)
{
if (adj[i].size() == 1) return leaf.push_back(i), void();
for (auto nxt : adj[i]) if (nxt != par) dfs(nxt, i);
}
int mx = 0, val = 0;
void dfs2(int i, int par, int sum)
{
if (sum > mx) mx = sum ,val = i;
for (auto nxt : adj[i]) if (nxt != par) dfs2(nxt, i, sum+1);
}
signed main()
{
lesgooo;
int n, u, v;
cin >> n;
for (int i =1 ; i < n; i++) cin >> u >> v, adj[--u].push_back(--v), adj[v].push_back(u);
int mxx = 0, vall = 0;
for (int i = 0; i < n; i++) if (adj[i].size() > mxx) mxx = adj[i].size(), vall = i;
dfs(vall, -1);
cout << (leaf.size()+1)/2 << endl;
for (int i = 0; i < leaf.size()/2; i++) cout << leaf[i]+1 << " " << leaf[leaf.size()/2+i]+1 << endl;
if (leaf.size()&1) dfs2(leaf.back(), -1, 0), cout << leaf.back()+1 << " " << val+1 << endl;
return 0;
}
Compilation message (stderr)
net.cpp: In function 'int main()':
net.cpp:27:51: warning: comparison of integer expressions of different signedness: 'std::vector<long long int>::size_type' {aka 'long unsigned int'} and 'long long int' [-Wsign-compare]
27 | for (int i = 0; i < n; i++) if (adj[i].size() > mxx) mxx = adj[i].size(), vall = i;
| ~~~~~~~~~~~~~~^~~~~
net.cpp:30:23: warning: comparison of integer expressions of different signedness: 'long long int' and 'std::vector<long long int>::size_type' {aka 'long unsigned int'} [-Wsign-compare]
30 | for (int i = 0; i < leaf.size()/2; i++) cout << leaf[i]+1 << " " << leaf[leaf.size()/2+i]+1 << endl;
| ~~^~~~~~~~~~~~~~~
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |