-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathEx_1_5_02.java
67 lines (60 loc) · 1.39 KB
/
Ex_1_5_02.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
package Ch_1_5;
import Ch_1_5.Ex_1_5_01._QuickFindUFCost;
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-19.
*/
public class Ex_1_5_02 {
public static class _QuickUnionUF{
private int[] id;
private int count;
private int arrayAccess;
public _QuickUnionUF(int N){
id = new int[N];
count = N;
for (int i = 0; i < N; i++) {
id[i] = i;
}
}
public int root(int p){
arrayAccess++;
while (id[p]!=p){
arrayAccess++;
p = id[p];
}
return p;
}
public void union(int p, int q){
int i = root(p);
int j = root(q);
if(i==j)
return;
id[i] = j;
arrayAccess++;
count--;
}
public boolean connected(int p, int q){
return root(p) == root(q);
}
public int count(){
return count;
}
public int arrayAccess(){
return arrayAccess;
}
}
public static void main(String[] args) throws FileNotFoundException {
System.setIn(new FileInputStream("Ch_1_5/Ex_1_5_01.txt"));
int N = StdIn.readInt();
_QuickUnionUF uf = new _QuickUnionUF(N);
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt();
uf.union(p, q);
}
StdOut.println(uf.arrayAccess());
}
}