forked from gdhucoder/Algorithms4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ex_1_5_11.java
81 lines (69 loc) · 1.73 KB
/
Ex_1_5_11.java
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
package Ch_1_5;
import Ch_1_4._Stopwatch;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* Created by HuGuodong on 2019-08-21.
*/
public class Ex_1_5_11 {
public static class _WeightedQuickFindUF {
int[] id;
int[] sz;
int count;
public _WeightedQuickFindUF(int N) {
id = new int[N];
count = N;
for (int i = 0; i < N; i++) {
id[i] = i;
}
sz = new int[N];
for (int i = 0; i < N; i++) {
sz[i] = 1;
}
}
public boolean connected(int p, int q) {
return id[p] == id[q];
}
public int find(int p) {
return id[p];
}
public void union(int p, int q) {
int pId = id[p];
int qId = id[q];
if (sz[p] < sz[q]) {
for (int i = 0; i < id.length; i++) {
if (id[i] == pId)
id[i] = qId;
}
sz[q] += sz[p];
} else {
for (int i = 0; i < id.length; i++) {
if (id[i] == qId)
id[i] = pId;
}
sz[p] += sz[q];
}
count--;
}
public int count() {
return count;
}
}
public static void main(String[] args) throws FileNotFoundException {
System.setIn(new FileInputStream("algdata/mediumUF.txt"));
int N = StdIn.readInt();
_WeightedQuickFindUF uf = new _WeightedQuickFindUF(N);
_Stopwatch time = new _Stopwatch();
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
if (uf.connected(p, q))
continue;
uf.union(p, q);
StdOut.printf("%d %d\n", p, q);
}
StdOut.println(uf.count() + " components, elapsed time :" + time.elapsedTime() + "s");
}
}