-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUF.java
More file actions
56 lines (51 loc) · 862 Bytes
/
UF.java
File metadata and controls
56 lines (51 loc) · 862 Bytes
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
package one;
public class UF {
private int[] id;//连通分量
private int count;//联通量
private int[] size;
public UF(int N){
this.id=new int[N];
this.count=N;
for(int i=0;i<N;i++){
id[i]=i;
}
this.size=new int[N];
for(int i=0;i<N;i++){
size[i]=1;
}
}
//p的标识符
public int find(int p){
while(p!=id[p]){
p=id[p];
}
return p;
}
//联通量
public int count(){
return count;
}
//联合p,q
public void union(int p,int q){
int pId=find(p);
int qId=find(q);
if(pId==qId){
return ;
}
if(size[pId]>size[qId]){
id[qId]=id[pId];
size[pId]+=size[qId];
}
else{
id[pId]=id[qId];
size[qId]+=size[pId];
}
count--;
}
//p和q两点是否相连
public boolean connected(int p,int q){
int pId=find(p);
int qId=find(q);
return pId==qId;
}
}