cf1406 C 树的重心

题意:https://www.luogu.com.cn/problem/CF1406C

思路:首先需要知道树的重心的一些性质,可以看看这篇文章

https://zhuanlan.zhihu.com/p/357938161

那么这题就是找出重心,如果有两个就将他的一个子树移到另一个重心上。

/*keep on going and never give up*/
#include<cstdio>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;
#define int long long
typedef pair<int, int> pii;
#define lowbit(x) x&(-x)
#define endl '\n'
#define wk is zqx ta die
vector<int> pl[100005];
int sz[100005], mss[100005];
vector<int> ctz;
int n;
void dfs(int p, int fa = 0) {
//	cout << p << endl;
	sz[p] = 1;
	mss[p] = 0;
	for (int i : pl[p]) {
		if (i == fa) {
			continue;
		}
		dfs(i, p);
		sz[p] += sz[i];
		mss[p] = max(mss[p], sz[i]);
	}
	mss[p] = max(mss[p], n - sz[p]);
	if (mss[p] <= n / 2) {
		ctz.push_back(p);
	}
}
signed main() {
	std::ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t;
	cin >> t;
	while (t--) {
		ctz.clear();
		cin >> n;
		for (int i = 1; i <= n; i++) {
			pl[i].clear();
		}
		for (int i = 1; i < n; i++) {
			int  u, v;
			cin >> u >> v;
			pl[u].push_back(v);
			pl[v].push_back(u);
		}
		if (n & 1) {
			cout << pl[1][0] << " " << 1 << endl;
			cout << 1 << " " << pl[1][0] << endl;
		} else {
			dfs(1);
			if (ctz.size() == 1) {
				cout << pl[1][0] << " " << 1 << endl;
				cout << 1 << " " << pl[1][0] << endl;
			} else {
				int a = ctz[0];
				int b = ctz[1];
//				cout << a << " " << b << endl;
				int h = 0;
				for (int i : pl[a]) {
					if (i == b) {
						continue;
					}
					h = i;
					break;
				}
				cout << a << " " << h << endl;
				cout << h << " " << b << endl;
			}
		}
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值