Cod sursa(job #2679613)

Utilizator mstevanStevan mstevan Data 30 noiembrie 2020 23:54:02
Problema Paduri de multimi disjuncte Scor 20
Compilator java Status done
Runda Arhiva educationala Marime 1.91 kb
import java.util.*;
import java.io.*;

public class Main {
    private static int n;
    private static int m;
    private static int [] parent;
    private static int [] rank;

    public static void main(String []args) {
        File inputFile = new File("disjoint.in");
        File outputFile = new File("disjoint.out");

        try {
            FileInputStream inputStream = new FileInputStream(inputFile);
            Scanner scanner = new Scanner(inputStream);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            PrintWriter writer = new PrintWriter(outputStream);

            n = scanner.nextInt(); // number of numbers
            m = scanner.nextInt(); // number of instructions
            parent = new int[n];
            rank = new int[n];
            for (int i = 0; i < n; i++){
                parent[i] = i;
                rank[i] = 1;
            }

            for (int i = 0; i < m; i++){
                int code = scanner.nextInt();
                int x = scanner.nextInt() - 1;
                int y = scanner.nextInt() - 1;
                if (code == 1)
                    union(x, y);
                else
                    if (root(x) == root(y))
                        writer.println("DA");
                    else
                        writer.println("NU");
            }

            inputStream.close();

            writer.close();
            outputStream.close();

        } catch (IOException e) {

        }
    }

    private static void union(int x, int y) {
        int rootx = root(x);
        int rooty = root(y);
        if (rank[rootx] >= rank[rooty])
            parent[rooty] = rootx;
        else
            parent[rootx] = rooty;
        if (rank[rootx] == rank[rooty])
            rank[rootx]++;
    }

    private static int root(int y) {
        if (y == parent[y])
            return y;
        parent[y] = root(parent[y]);
        return parent[y];
    }
}