Submission #51344

#TimeUsernameProblemLanguageResultExecution timeMemory
51344faishol27Network (BOI15_net)C++14
0 / 100
22 ms23948 KiB
#include <bits/stdc++.h>
using namespace std;

typedef pair<int, int> pi;
#define PUB push_back
#define fi first
#define se second

int N, root, cnt = 0, tot_leaf = 0;
vector<int> adjL[500005], leaf[500005];
pi data[500005]; // {id, byk_leaf}

void find_root(){
	for(int i=1;i<=N;i++){
		if(adjL[i].size() > 1){
			root = i;
			break;
		}
	}
}

void find_leaf(int prn, int pos){
	if(adjL[pos].size() == 1){
		leaf[cnt].PUB(pos);
		tot_leaf++;
		data[cnt].se++;
		return;
	}

	for(auto nxt:adjL[pos]){
		if(nxt == prn) continue;
		find_leaf(pos, nxt);
	}
}

bool cmp(pi a, pi b){
	return a.se > b.se;
}

void print_ans(){
	int pos = 1, kanan = cnt-1;
	sort(data, data+cnt, cmp);

	cout << (tot_leaf+1)/2 << endl;
	
	for(int i=0;i<cnt;i++){
		if(data[i].se == 0) continue;
		
		while(data[i].se > 0){
			int a = leaf[data[i].fi].back(),
				b = leaf[data[pos].fi].back();
			cout << a << " " << b << endl;

			leaf[data[pos].fi].pop_back(); leaf[data[i].fi].pop_back();
			data[pos].se--; data[i].se--;

			pos++;
			if(pos > kanan){
				while(data[kanan].se == 0){
					kanan--;
				}
				pos = i+1;
				if(data[pos].se == 0) break;
			}
		}

		while(data[i].se > 0){
			if(data[i].se == 1){
				cout << leaf[data[i].fi].back() << " " << root << endl;
				data[i].se--;
			}else{
				cout << leaf[data[i].fi].back(); leaf[data[i].fi].pop_back();
				cout << " " << leaf[data[i].fi].back(); leaf[data[i].fi].pop_back();
				data[i].se -= 2;
			}
		}
	}
}

int main(){
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

	cin >> N;
	for(int i=0;i<N-1;i++){
		int x, y;
		cin >> x >> y;
		
		adjL[x].PUB(y);
		adjL[y].PUB(x);
	}

	find_root();

	for(auto nxt:adjL[root]){
		data[cnt] = {cnt, 0};
		find_leaf(root, nxt);
		cnt++;
	}
	// for(int i=0;i<cnt;i++){
	// 	cout << data[i].fi << " -> ";
	// 	for(auto elm:data[i])
	// }
	print_ans();

	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...