-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWeightedQuickUnion.java
More file actions
68 lines (62 loc) · 1.48 KB
/
WeightedQuickUnion.java
File metadata and controls
68 lines (62 loc) · 1.48 KB
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
public class WeightedQuickUnion {
int[] array;
int[] sz;
public WeightedQuickUnion(int N)
{
array = new int[N];
sz = new int[N];
for (int i = 0; i < N; i++)
{
array[i] = i;
sz[i] = 1;
}
}
public int root(int p)
{
while (p != array[p])
p = array[p];
return p;
}
public boolean connected(int p,int q)
{
return root(p) == root(q);
}
public void union(int p, int q)
{
int i = root(p);
int j = root(q);
if (i == j)
return;
if (sz[i] < sz[j])
{
array[i] = j;
sz[j] += sz[i];
}
else
{
array[j] = i;
sz[i] += sz[j];
}
for (int l = 0; l < array.length; l++)
System.out.print(array[l] + " ");
System.out.println();
}
public static void main(String[] args)
{
int N = StdIn.readInt();
WeightedQuickUnion uf = new WeightedQuickUnion(N);
while (!StdIn.isEmpty())
{
int p = StdIn.readInt();
int q = StdIn.readInt();
if (!uf.connected(p, q))
{
uf.union(p, q);
}
else
{
StdOut.println(p + " and " + q + " are already connected." );
}
}
}
}