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

  • 相关阅读:
    AGC037F Counting of Subarrays
    AGC025F Addition and Andition
    CF506C Mr. Kitayuta vs. Bamboos
    AGC032D Rotation Sort
    ARC101F Robots and Exits
    AGC032E Modulo Pairing
    CF559E Gerald and Path
    CF685C Optimal Point
    聊聊Mysql索引和redis跳表
    什么是线程安全
  • 原文地址:https://www.cnblogs.com/kakamilan/p/3110118.html
Copyright © 2011-2022 走看看