Cod sursa(job #2361746)

Utilizator djxaosjqsDan Graur djxaosjqs Data 2 martie 2019 18:16:43
Problema Paduri de multimi disjuncte Scor 20
Compilator java Status done
Runda Arhiva educationala Marime 1.66 kb
import java.lang.*;
import java.util.*;
import java.io.*;

class DisjointSet {
    int value;
    int rank;
    DisjointSet parent;

    DisjointSet(int value) {
        this.rank = 0;
        this.value = value;
        this.parent = this;
    }

    public DisjointSet getRoot() {
        if (this.parent != this)
            this.parent = this.parent.getRoot();

        return this.parent;
    }

    public static void joinSets(DisjointSet first, DisjointSet second) {
        if (first == second)
            return;

        if (first.rank == second.rank) {
            ++first.rank;
            second.parent = first;
        } else if (first.rank < second.rank) {
            first.parent = second;
        } else {
            second.parent = first;
        }
    }

}

public class Main {

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(new File("disjoint.in"));
        PrintWriter out = new PrintWriter(new File("disjoint.out"));

        int n = in.nextInt();
        int m = in.nextInt();

        // Construct the disjoint sets
        DisjointSet[] sets = new DisjointSet[n];

        for (int i = 0; i < n; ++i)
            sets[i] = new DisjointSet(i + 1);

        // Execute the operations
        for (int i = 0; i < m; ++i) {
            int opType = in.nextInt();
            int x = in.nextInt();
            int y = in.nextInt();
            
            if (opType == 1) 
                DisjointSet.joinSets(sets[x - 1].getRoot(), sets[y - 1].getRoot());
            else 
                out.println(sets[x - 1].getRoot() == sets[y - 1].getRoot() ? "DA" : "NU");
        }

        in.close();
        out.close();
    }

}