并查集
1 #include<iostream>
2 #include<cstring>
3 using namespace std;
4
5 int f[30001],r[30001];
6 int m,n;
7 void Init()
8 {
9 for(int i=0;i<m;++i) f[i]=i;
10 memset(r,0,sizeof(r));
11 }
12
13 int father(int k)
14 {
15 if(k !=f[k])
16 return father(f[k]);
17 return f[k];
18 }
19
20 void unionset(int k,int t)
21 {
22 int i=father(k);
23 int j=father(t);
24 f[j]=i;
25 /*if(r[i]<r[j])
26 f[i]=j;
27 else
28 {
29 f[j]=i;
30 if(r[i]==r[j])
31 r[i]++;
32 }*/
33
34 }
35 void readData()
36 {
37 int i,j,s,k,t;
38 while(cin>>m>>n)
39 {
40 if(m==0 && n==0) break;
41 Init();//
42 for(int i=1;i<=n;++i)
43 {
44 cin>>s;
45 cin>>k;
46 for(j=1;j<s;++j)
47 {
48 cin>>t;
49 if(father(k)!=father(t))
50 {
51 unionset(k,t);
52 }
53 k=t;
54 }
55 }
56
57 j=father(0);
58 int ans=1;
59 for(i=1;i<m;++i)
60 {
61 if(j==father(i)) ans++;
62 }
63 cout<<ans<<endl;
64 }
65 }
66 int main()
67 {
68 //Init();
69 freopen("a.txt","r",stdin);
70 readData();
71 return 0;
72 }