I am trying to solve a Disjoint Sets problem, using Sedgewick Union Find (UF) from here: https://algs4.cs.princeton.edu/code/javadoc/edu/princeton/cs/algs4/UF.html
However, I get a wrong output whenever there is a "move" operation (i.e. input value 2).
Example input
4 9
0 0 1
1 0 1
0 0 1
1 1 2
0 1 2
0 0 3
2 2 3
0 0 1
0 1 2
Expected output My output
0 0
1 1
1 1
0 0
1 1
0 1
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.UF;
public class Disjoint_Sets {
public static void main(String[] args) {
int n = StdIn.readInt();
int m = StdIn.readInt();
UF uf = new UF(n);
for (int i = 0; i < m; i++) {
int query = StdIn.readInt();
int s = StdIn.readInt();
int t = StdIn.readInt();
if (query == 0) {
if (uf.find(s) == uf.find(t)) {
StdOut.println("1");
} else {
StdOut.println("0");
}
} else if (query == 1) {
uf.union(s, t);
} else {
int temp = s;
s = t;
t = temp;
uf.union(s, t);
}
}
}
}
I think my problem is the final else branch I have, but I don't know what do? 😦