【并查集】HDOJ tree 5606

来源:互联网 发布:淘宝10.11事变 编辑:程序博客网 时间:2024/05/16 05:53

tree

                                          Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
                                                             Total Submission(s): 448    Accepted Submission(s): 222



Problem Description
There is a tree(the tree is a connected graph which containsn points and n1 edges),the points are labeled from 1 to n,which edge has a weight from 0 to 1,for every point i[1,n],you should find the number of the points which are closest to it,the clostest points can containi itself.
 

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

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

T50,n105,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 ansi is the answer to point i,you only need to output,ans1 xor ans2 xor ans3.. ansn.
 

Sample Input
131 2 02 3 1
 

Sample Output
1in the sample.$ans_1=2$$ans_2=2$$ans_3=1$$2~xor~2~xor~1=1$,so you need to output 1.
 

Source
BestCoder Round #68 (div.2)
 

Recommend
hujie   |   We have carefully selected several similar problems for you:  5609 5608 5607 5605 5604

题意:

有n个点,给n-1个边和权值w,找出i点所有距离为0的点的数量ansi,XOR所有点的结果ansi。

解题思路:

并查集~把所有权值为0点的并到一个连通图上,然后遍历所有的点的根节点的ans值进行操作。

AC代码:

#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int MAXN = 100000+10;int ans[MAXN];int p[MAXN];void init(int n){    for(int i=1;i<=n;i++){        p[i]=i;ans[i]=0;    }}int find(int x){    int son,temp;    son=x;    while(x!=p[x]){        x=p[x];    }    while(son!=x){        temp=p[son];        p[son]=x;        son=temp;    }    return x;}void merge(int x,int y){    x=find(x);y=find(y);    if(x!=y)p[x]=y;}int main(){    int t;    scanf("%d",&t);    while(t--){        int n;        scanf("%d",&n);        init(n);        int u,v;        int w;        for(int i=0;i<n-1;i++){            scanf("%d%d%d",&u,&v,&w);            if(!w)merge(u,v);        }        for(int i=1;i<=n;i++){ //一定要进行一次压缩            find(i);        }        for(int i=1;i<=n;i++){            ans[p[i]]++;        }        int res=0;        for(int i=1;i<=n;i++){            res^=ans[p[i]];        }        printf("%d\n",res);    }    return 0;}


0 0
原创粉丝点击