public class ConnectingGraph {
private int[] father;
public ConnectingGraph(int n) {
// initialize your data structure here.
father = new int[n + 1];
for (int i = 1; i < n + 1; i++) {
father[i] = i;
}
}
//return the father id
private int find(int a) {
if (father[a] == a) return a;
father[a] = find(father[a]);
return father[a];
}
public void connect(int a, int b) {
// Write your code here
int rootA = find(a);
int rootB = find(b);
if (rootA != rootB) {
father[rootA] = rootB;
}
}
public boolean query(int a, int b) {
// Write your code here
int rootA = find(a);
int rootB = find(b);
return rootA == rootB;
}
}
No comments:
Post a Comment