제출 #1345114

#제출 시각아이디문제언어결과실행 시간메모리
1345114tkm_algorithmsNetwork (BOI15_net)C++20
100 / 100
223 ms68188 KiB
#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using P = pair<int, int>;
#define all(x) x.begin(), x.end()
#define rep(i, l, n) for (int i = l; i < (n); ++i)
#define sz(x) (int)x.size()
const char nl = '\n';
const int N = 5e5+10;
vector<int> g[N], A[N];
int cnt[N], idx;
int ex[N];

void calc(int nd, int p) {
	cnt[nd] = sz(g[nd]) ==1;
	for (auto i: g[nd])
		if (i != p)
			calc(i, nd),
			cnt[nd] += cnt[i];
}

int s = 1;

int dfs(int nd, int p) {
	for (auto i: g[nd])
		if (i != p && cnt[i] > cnt[s]-cnt[i])return dfs(i, nd);
	return nd;
}

void gos(int nd, int p) {
	if (sz(g[nd]) == 1)A[idx].push_back(nd), ex[idx] = nd;
	for (auto i: g[nd])
		if (i != p)gos(i, nd);
}

void solve() {
	int n; cin >> n;
	int res = n;
	rep(i, 0, n-1) {
		int u, v; cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
		if (sz(g[u]) == 2)res -= 1;
		if (sz(g[v]) == 2)res -= 1;
	}
	
	cout << (res+1)/2 << nl;
	if (sz(g[1]) == 1)s = g[s][0];
	calc(s, -1);
	int lc = dfs(s, -1);
	priority_queue<P> pq;
	for (auto i: g[lc]) {
		gos(i, lc), idx += 1;
		pq.push({sz(A[idx-1]), idx-1});
	}
	
	while (!pq.empty()) {
		P a = pq.top(); pq.pop();
		P b = pq.top(); pq.pop();
		if (a.first == 0)break;
		if (b.first == 0) {
			a.first -= 1;
			cout << A[a.second].back() << " " << ex[b.second] << nl;
			A[a.second].pop_back();
			pq.push(a), pq.push(b);
			continue;
		} else {
			cout << A[a.second].back() << " " << A[b.second].back() << nl;
			A[a.second].pop_back(), A[b.second].pop_back();
			a.first -= 1, b.first -= 1;
			pq.push(a), pq.push(b);
		}
	}
}

int32_t main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    solve();
    return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...