-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUva10583.cpp
More file actions
57 lines (55 loc) · 953 Bytes
/
Copy pathUva10583.cpp
File metadata and controls
57 lines (55 loc) · 953 Bytes
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
#include <iostream>
#include <vector>
using namespace std ;
typedef vector<int> vi ;
class UnionFind {
private:
vi p , rank ;
int numSets ;
public:
UnionFind(int N){
numSets = N ;
rank.assign(N,0);
p.assign(N,0);
for(int i = 0 ; i < N ; i++){
p[i] = i ;
}
}
int findSet(int i){
return (p[i] == i) ? i : p[i] = findSet(p[i]) ;
}
bool isSameSet(int i , int j){
return findSet(i) == findSet(j) ;
}
void unionSet(int i , int j){
if(!isSameSet(i,j)){
numSets-- ;
int x = findSet(i) ;
int y = findSet(j) ;
if( rank[x] > rank[y] ){
p[y] = x ;
} else{
p[x] = y ;
if( rank[x] == rank[y] ){
rank[y]++ ;
}
}
}
}
int numDisjointSets(){
return numSets ;
}
} ;
int main()
{
int n , m , x , y ,c = 1 ;
while(cin>>n>>m , n ){
UnionFind uf(n);
while(m--){
cin >> x >> y ;
uf.unionSet(x-1,y-1) ;
}
cout << "Case "<< c++ << ": " << uf.numDisjointSets() << "\n" ;
}
return 0 ;
}