zoukankan      html  css  js  c++  java
  • hdu5606 tree (并查集)

    tree

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


    Problem Description
    There is a tree(the tree is a connected graph which contains n 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 contain i 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
    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个节点的树,有的边权是1有的是0,是0表示距离近,而且比如1和2是0,1和3也是0,那么2和3之间也是0,转化为并查集,顺便路径压缩;
    AC代码:
    #include <iostream>
    #include <cstdio>
    #include <map>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    const int N=1e6+5;
    int flag[N],p[N];
    int findset(int x)
    {
        if(x!=p[x])return p[x]=findset(p[x]);
        return x;
    }
    int main()
    {
        int T,n,u,v,w;
        scanf("%d",&T);
        while(T--)
        {
           scanf("%d",&n);
           for(int i=1;i<=n;i++)
           {
               flag[i]=0;
               p[i]=i;
           }
           for(int i=0;i<n-1;i++)
           {
               scanf("%d%d%d",&u,&v,&w);
               if(w==0)
               {
                   int a=findset(u);
                   int b=findset(v);
                   p[a]=b;
               }
           }
           for(int i=1;i<=n;i++)
           {
               flag[findset(i)]++;
           }
           int ans=flag[findset(1)];
           for(int i=2;i<=n;i++)
           {
               ans=(ans^flag[findset(i)]);
           }
           printf("%d
    ",ans);
        }
        return 0;
    }
  • 相关阅读:
    git创建版本库
    DataSet的加密解密
    在InstallShield中加密字符串,在C#中解密
    asp.net后台长时间操作时,向前台输出“请等待"信息的方法
    DataSet的加密解密(续)
    XXTEA加密算法的InstallShield 脚本实现
    c#如何监视文件或者文件夹的变化
    wpf制作毛玻璃效果按钮的代码
    WPF中用于Path的Geometry MiniLanguage
    如何在非英文环境中正确显示数字
  • 原文地址:https://www.cnblogs.com/zhangchengc919/p/5161917.html
Copyright © 2011-2022 走看看