-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDisjointSet.java
79 lines (67 loc) · 1.66 KB
/
DisjointSet.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
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class DisjointSet {
protected Node[] sets;
public DisjointSet(int n) {
sets = new Node[n];
for(int i = 0; i < n; i++){
this.sets[i] = new Node(i);
}
System.out.println("-");
}
public void union(int a, int b){
a = findPredecessor(a);
b = findPredecessor(b);
if(sets[a].cost > sets[b].cost){
sets[b].predecessor = a;
System.out.println("-");
}
else if(sets[a].cost < sets[b].cost){
sets[a].predecessor = b;
System.out.println("-");
}
else{
sets[a].predecessor = b;
sets[b].cost++;
System.out.println("-");
}
}
public boolean compare(int a, int b) {
a = findPredecessor(a);
b = findPredecessor(b);
if(a == b){
System.out.println("true");
return true;
}
else{
System.out.println("false");
return false;
}
}
private int findPredecessor(int index){
while(index != sets[index].predecessor){
index = sets[index].predecessor;
}
return index;
}
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("conjuntos2.in");
BufferedReader br = new BufferedReader(file);
String valores = br.readLine();
DisjointSet set = new DisjointSet(Integer.parseInt(valores));
while (br.ready()) {
valores = br.readLine();
String[] vSplited = valores.split(" ");
String type = vSplited[0];
String v1 = vSplited[1];
String v2 = vSplited[2];
if (type.equals("union")) {
set.union(Integer.parseInt(v1), Integer.parseInt(v2));
} else if (type.equals("compare")) {
set.compare(Integer.parseInt(v1), Integer.parseInt(v2));
}
}
file.close();
}
}