#Disjoint Sets (Union Find)

1 messages · Page 1 of 1 (latest)

rough sable
#

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? 😦

tall pagoda
#

@rough sable do you still need help?

rough sable
#

Can't figure the move one out

tall pagoda
#

I feel like the Sedgewick Union Find that you use doesnt have any way to handle the move operation lol

#

do you have to use that library ? @rough sable

rough sable
#

I think I would have to come up with a method for that myself

tall pagoda
#

something probably dumb that could work is take note of all the sets, then create a new uf and remake all the set

rough sable
rough sable
tall pagoda
#

this doesnt look right to me

#

union put 2 sets together

#

I dont see how union(s,s+1) would solve anything

#

There is no way to remove an element from a set from what I can tell from that library