-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyWeightedQuickUnionPC.java
110 lines (101 loc) · 2.33 KB
/
MyWeightedQuickUnionPC.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Tony
*/
public class MyWeightedQuickUnionPC {
private int[] id;
private int[] sz;
private int count;
/**
* Initializes an empty union-find data structure with N isolated components
* @param N number of objects
*/
public MyWeightedQuickUnionPC(int N){
count = N;
id = new int[N];
sz = new int[N];
for(int i=0; i<N; i++){
id[i] = i;
sz[i] = 1;
}
}
/**
*
* @param p
* @return
*/
public int find(int p){
while (p != id[p])
p = id[p];
return p;
}
/**
*
* @param p
* @param q
* @return
*/
public boolean connected(int p, int q){
return find(p) == find(q);
}
/**
*
* @param p
* @param q
*/
public void union(int p, int q){
int rootP = find(p);
int rootQ = find(q);
if(rootP == rootQ){
return;
}
int root_new;
if(sz[rootP] < sz[rootQ]){
id[rootP] = id[rootQ];
sz[rootQ] +=sz[rootP];
root_new = rootQ;
}
else{
id[rootQ] = id[rootP];
sz[rootP] +=sz[rootQ];
root_new = rootP;
}
while(id[p] != root_new){
int tmp = id[p];
id[p] = root_new;
p = tmp;
}
while(id[q] != root_new){
int tmp = id[q];
id[q] = root_new;
q = tmp;
}
count--;
}
/**
*
* @param args
*/
public static void main(String[] args){
In in = new In(args[0]);
int N = in.readInt();
MyWeightedQuickUnionPC pc = new MyWeightedQuickUnionPC(N);
while(!in.isEmpty()){
int p = in.readInt();
int q = in.readInt();
if(pc.connected(p, q))
continue;
pc.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(pc.count + " components");
for(int i=0; i<N; i++){
StdOut.println(pc.id[i]);
}
}
}