HDU 5606 Tree【并查集】

本文介绍了一种利用并查集解决树形结构中点间距离问题的方法,通过合并权重为0的边连接的节点集合,快速计算每个节点与其相同距离节点的数量。并提供了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

There is a tree(the tree is a connected graph which contains nnpoints and n−1n−1 edges),the points are labeled from 1 to nn,which edge has a weight from 0 to 1,for every point i∈[1,n]i∈[1,n],you should find the number of the points which are closest to it,the clostest points can contain ii itself. 

Input

the first line contains a number T,means T test cases. 

for each test case,the first line is a nubmer nn,means the number of the points,next n-1 lines,each line contains three numbers u,v,wu,v,w,which shows an edge and its weight. 

T≤50,n≤105,u,v∈[1,n],w∈[0,1]T≤50,n≤105,u,v∈[1,n],w∈[0,1]

Output

for each test case,you need to print the answer to each point. 

in consideration of the large output,imagine ansiansi is the answer to point ii,you only need to output,ans1 xor ans2 xor ans3.. ansnans1 xor ans2 xor ans3.. ansn. 

Sample Input

1
3
1 2 0
2 3 1

Sample Output

1

in the sample.

$ans_1=2$

$ans_2=2$

$ans_3=1$

$2~xor~2~xor~1=1$,so you need to output 1.

 题目大意:

        给定n个点,n-1条带权边,边的权值为0或1,求每个点有多少与它距离为0的点,视点到自身的距离为0;

解题思路:

        并查集,当两点之间的权值为0时,合并两集合,用标记节点记录 标记节点 存在 的 集合中的元素数目

实现代码:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn=100000+5;

//并查集
int fa[maxn],num[maxn];
int findset(int x){
    return fa[x]==x? x: fa[x]=findset(fa[x]);
}
void bin(int u,int v){
    int fu=findset(u);
    int fv=findset(v);
    if(fu!=fv){
        fa[fv]=fu;  //改变父节点为fu
        num[fu]+=num[fv];
    }
}

int main()
{
    int T;
    scanf("%d",&T);
    while(T--){
        for(int i=1;i<100003;i++){
            fa[i]=i;
            num[i]=1;
        }

        int n;
        scanf("%d",&n);

        for(int i=1;i<=n-1;i++){
            int u,v,w;
            scanf("%d%d%d",&u,&v,&w);
            if(w==0){
                bin(u,v);
            }
        }

        int ans=0;
        for(int i=1;i<=n;i++){  //找到每一个节点的父节点的集合
            ans^=num[findset(i)];
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值