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 speed ios_base::sync_with_stdio(0); cin.tie(0)
#define all(x) (x).begin(),(x).end()
#define F first
#define S second
//#pragma GCC optimize("O3,unroll-loops")
//#pragma GCC target("avx,avx2")
//#pragma GCC target("popcnt")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef double db;
typedef long double ldb;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
const ll MAX=2e5+10,P=1e9+7;
const ll INF=0x3f3f3f3f,oo=0x3f3f3f3f3f3f3f3f;
const ldb eps=1e-6;
const ldb PI=acos(-1.0);
const int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
template<typename T>
using vvector = vector<vector<T>>;
vector<ll> dfs(int v,int p,vvector<int> &G,vector<pii> &ans) {
vector<ll> lv;
for (int i:G[v]) {
if (i==p) continue;
auto nlv = dfs(i,v,G,ans);
while (!lv.empty() and !nlv.empty() and lv.size()+nlv.size()>2) {
ans.emplace_back(lv.back(),nlv.back());
lv.pop_back();
nlv.pop_back();
}
while (!nlv.empty()) {
lv.push_back(nlv.back());
nlv.pop_back();
}
}
if (G[v].size()==1) lv.push_back(v);
return lv;
}
int main() {
speed;
int n;
cin>>n;
vvector<int> G(n+1);
for (int i=0;i<n-1;i++) {
int a,b;
cin>>a>>b;
G[a].push_back(b);
G[b].push_back(a);
}
int rot=0;
for (int i=1;i<=n;i++) {
if (G[i].size()>1) {
rot=i;
break;
}
}
vector<pii> ans;
auto lv = dfs(rot,0,G,ans);
if (lv.size()==2) ans.emplace_back(lv[0],lv[1]);
else if (lv.size()==1) ans.emplace_back(lv[0],rot);
cout<<ans.size()<<"\n";
for (auto [a,b]:ans) cout<<a<<" "<<b<<"\n";
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |