Alice wants to delete a tree.
She can do the following operations:
-
Delete: Delete a vertex in the tree and all the edges connected to it.
-
Shrink: Choose a vertex x that has exactly two vertices connected to it; suppose the vertices are u,v, Alice can delete x and the edges (u,x),(x,v) and add a new edge (u,v).
Alice wants to achieve her goal using the least number of Delete operations. Please help her.
题意:
可以对一棵树进行Delete和Shrink两个操作,使用最少的Delete删除这棵树
我们可以选择先删掉1号结点,使2 3相连,再Delete 3号结点
删掉2号结点,使4 5相连,此时仅剩4、5结点,我们通过两次Delete删除
这样的一棵树,需要3次Delete操作删除
通过观察发现,删除父节点并不会改变两个子节点的状态,我们需要尽可能地通过Shrink操作删去所有父节点,剩下的叶子节点使用Delete操作删除
哦,到这里终于明白了,这道题其实就是求叶子节点的个数
代码
#include <iostream>
using namespace std;
const int Maxn = 1000010;
int T, n,x,y;
int cnt[Maxn];
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d", &n);
int ans=n;
for(int i=1;i<=n;i++)cnt[i]=0;
for(int i=1;i<n;i++){
scanf("%d%d",&x,&y);
cnt[x]++;
cnt[y]++;
if(cnt[x]==2)ans--;
if(cnt[y]==2)ans--;
}
printf("%d\n",ans);
}
}