-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob_01197.cpp
83 lines (76 loc) · 2.05 KB
/
prob_01197.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
using namespace std;
#define vi vector<int>
#define vii vector<pair<int,int> >
#define vvi vector<vi>
#define vvii vector<vii>
#define sc(n) scanf("%d",&n)
#define repf(i,a,b) for(i=a;i<b;++i)
#define repb(i,a,b) for(i=a;i>b;--i)
#define gc getchar_unlocked
class UFDS{
vi parent,rank;
int num_sets; // to answer queries that ask for the numbr of different sets
vi set_size; // used to store the size of the set element i belongs to
public:
UFDS(int n){
parent.assign(n+1,0);
rank.assign(n+1,0);
set_size.assign(n+1,1);
for(int i=0;i<=n;++i)
parent[i]=i;
num_sets= n;
}
bool is_same_set(int i, int j){
return find_set(i) == find_set(j);
}
void union_set(int i, int j){
int x= find_set(i), y= find_set(j);
if(x!=y){
--num_sets;
if(rank[x]==rank[y]){
parent[x]= y;
++rank[y];
}else{
if(rank[x]>rank[y])
parent[y]= x;
else parent[x]= y;
}
set_size[x] = set_size[y] =(set_size[x]+set_size[y]);
}
}
int find_set(int i){
return (i==parent[i]?i:(parent[i]=find_set(parent[i])));
}
int find_set_size(int i){
return set_size[find_set(i)];
}
int num_disjoint_sets(){
return num_sets;
}
};
int main(){
int i,j,k,n,m;
int student,prev_student;
while(scanf("%d%d",&n,&m),n|m){
UFDS ufds(n);
repf(i,0,m){
sc(k);
sc(prev_student);
repf(j,1,k){
sc(student);
ufds.union_set(prev_student,student);
prev_student= student;
}
}
cout << ufds.find_set_size(0)<<endl;
}
}