• tree(并查集)


    tree

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

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5606

    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
     
     
    题解: 把每条边权是1的边断开,发现每个离他最近的点个数就是他所在的联通快的大小,开一个并查集,每次读到编圈是0的边就合并,最后结果就是每个点的父亲的孩子个数加1
    太久没有打并查集了水一水
     1 #include<cstdio>
     2 #include<cstring>
     3 #include<string>
     4 using namespace std;
     5 #define N 100006
     6 int n;
     7 int fa[N];
     8 int num[N];
     9 void init(){
    10   for(int i = 0; i < N; i++) fa[i] = i;
    11 }
    12 int find(int x){
    13   return fa[x]==x?x:fa[x]=find(fa[x]);
    14 }
    15 void merge(int x, int y){
    16   int root1 = find(x);
    17   int root2 = find(y);
    18   if(root1==root2) return;
    19   fa[root1] = root2;
    20 }
    21 
    22 int main()
    23 {
    24   int t;
    25   scanf("%d",&t);
    26   while(t--)
    27   {
    28     init();
    29     scanf("%d",&n);
    30     for(int i = 0; i < n-1; i++)
    31     {
    32       int a, b, c;
    33       scanf("%d%d%d",&a,&b,&c);
    34       if(c==0){
    35         merge(a,b);
    36       }
    37     }
    38     memset(num,0,sizeof(num));
    39     for(int i = 1; i <= n; i++)
    40     {
    41       int r = find(i);
    42       num[r]++;
    43     }
    44     int ans = 0;
    45     for(int i = 1; i <= n; i++)
    46     {
    47       ans = (ans^num[find(i)]);
    48     }
    49     printf("%d
    ",ans);
    50   }
    51   return 0;
    52 }
  • 相关阅读:
    mysql备份
    Linux 配置参考
    oracle补丁安装
    多智能体城市交通计算综合应用
    基于纳什均衡的多智能体强化学习交通信号控制
    多智能体强化学习在城市交通信号控制中的研究与应用- 笔记
    Sarsa与Q-learning
    Pandas笔记
    Python学习笔记
    Game Theory and Multi-agent Reinforcement Learning笔记 下
  • 原文地址:https://www.cnblogs.com/shanyr/p/5203299.html
Copyright © 2020-2023  润新知