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

posted on 2013-05-31 12:06  kakamilan  阅读(176)  评论(0编辑  收藏  举报

导航