-
Notifications
You must be signed in to change notification settings - Fork 15
/
City and Flood.cpp
102 lines (73 loc) · 1.88 KB
/
City and Flood.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
public class GFG
{
class Node
{
int data ;
Node parent;
int rank;
}
HashMap<Integer, Node> m= new HashMap<>();
public void makeset(int data)
{
Node node = new Node();
node.data=data;
node.parent=node;
node.rank=0;
m.put(data,node);
}
public boolean union(int data1,int data2)
{
Node node1 = m.get(data1);
Node node2 =m.get(data2);
Node parent1= findset(node1);
Node parent2 = findset(node2);
if(parent1.data==parent2.data)
return false;
else
{
if(parent1.rank>=parent2.rank)
{
if(parent1.rank==parent2.rank)
parent1.rank++;
parent2.parent=parent1;
}
else
parent1.parent=parent2;
}
return true;
}
public int findset(int data)
{return findset(m.get(data)).data;}
public Node findset(Node node)
{
Node parent = node.parent;
if(parent==node)
return parent;
node.parent = findset(node.parent);
return node.parent;
}
public static void main (String[] args) {
int i;
Scanner s = new Scanner(System.in);
GFG ds = new GFG();
int n = s.nextInt();
for(i=1;i<=n;i++)
ds.makeset(i);
int q = s.nextInt();
while(q-->0)
{
int a = s.nextInt();
int b = s.nextInt();
ds.union(a,b);
}
Set<Integer> my = new HashSet<Integer>();
for(i=1;i<=n;i++)
{
my.add(ds.findset(i));
}
System.out.println(my.size());
}
}