Codeforces Round 915 (Div. 2)------>B. Begginer‘s Zelda

1.思路:做这道题首先要想按照平常思维既然要操作次数最少,那么就等于每次要连接尽可能多的点,那么在一棵树中那两个点之间的路径经过的点是最多的,当然是两个距离最远的叶子节点(度为1的点),想到这就知道,其实我们只需要统计叶子节点的个数n,因为两两匹配,又考虑到叶子节点的个数可能是奇数,所要想上取整----> (n+2-1)/2。

2.代码


#include <iostream>
#include<algorithm>
using namespace std;

const int N = 1e5;
int d[N];

void sovle() {

	memset(d, 0, sizeof d);

	int n;
	cin >> n;

	for (int i = 0; i < n - 1; i++) {
		int x, y;
		cin >> x >> y;
//记录每个点的度
		d[x]++, d[y]++;
	}

	int cnt = 0;
//统计度为1的点
	for (int i = 1; i <= n; i++) {
		if (d[i] == 1) cnt++;
	}
//向上取整求次数
	int res = (cnt + 1) / 2;
	cout << res << endl;
}

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);

	int t;
	cin >> t;

	while (t--) {
		sovle();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值