zoukankan      html  css  js  c++  java
  • poj 1611

    并查集的入门题吧,了解了简单的思想~~~

     1 #include <iostream>
     2 #include <string>
     3 #include <vector>
     4 #include <cstdlib>
     5 #include <cmath>
     6 #include <map>
     7 #include <algorithm>
     8 #include <list>
     9 #include <ctime>
    10 #include <set>
    11 #include <string.h>
    12 #include <queue>
    13 #include <cstdio>
    14 #define CLR(arr, what) memset(arr, what, sizeof(arr))
    15 typedef long long ll;
    16 const int MAX = 100000;
    17 using namespace std;
    18 
    19 
    20 int n, m, i, j;
    21 int father[30005], num[30005];
    22 
    23 void makeSet(int n)
    24 {
    25     for(i = 0; i < n; i++)
    26     {
    27         father[i] = i; //使用本身做根
    28         num[i] = 1;
    29     }
    30 }
    31 int findSet(int x)
    32 {
    33     if(father[x] != x) //合并后的树的根是不变的
    34     {
    35         father[x] = findSet(father[x]);
    36     }
    37     return father[x];
    38 }
    39 
    40 void Union(int a, int b)
    41 {
    42     int x = findSet(a);
    43     int y = findSet(b);
    44     if(x == y)
    45     {
    46         return;
    47     }
    48     if(num[x] <= num[y])
    49     {
    50         father[x] = y;
    51         num[y] += num[x];
    52     }
    53     else
    54     {
    55         father[y] = x;
    56         num[x] += num[y];
    57     }
    58 }
    59 
    60 int main()
    61 {
    62     while(scanf("%d %d", &n, &m)!=EOF && n != 0)
    63     {
    64         makeSet(n);
    65         for(i = 0; i < m; i++)
    66         {
    67             int count, first, b;
    68             scanf("%d %d",&count, &first);
    69             for(j = 1; j < count; j++)
    70             {
    71                 scanf("%d",&b);
    72                 Union(first,b);
    73             }
    74         }
    75         printf("%d\n",num[findSet(0)]);
    76     }
    77     return 0;
    78 }

    from kakamilan

  • 相关阅读:
    JAVA 异常
    JAVA 接口的基本语法
    JAVA 访问权限
    Linux shell 函数应用示例02
    Linux shell 函数应用示例01
    Linux shell while循环语句
    Linux shell 中断循环语句
    Linux shell for循环结构
    测试用例基本概念
    软件测试原则
  • 原文地址:https://www.cnblogs.com/kakamilan/p/3110118.html
Copyright © 2011-2022 走看看