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;
}