Cod sursa(job #1741680)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 14 august 2016 18:18:22
Problema Paduri de multimi disjuncte Scor 100
Compilator java Status done
Runda Arhiva educationala Marime 2.7 kb
import java.io.*;
import java.util.StringTokenizer;

public class Main {

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

        int N = in.nextInt();
        int M = in.nextInt();

        DisjointSet DSU = new DisjointSet(N);

        for (int i = 0; i < M; i++) {
            int t = in.nextInt();
            int x = in.nextInt();
            int y = in.nextInt();

            if (t == 1)
                DSU.union(x, y);
            else
                out.println(DSU.connected(x, y) ? "DA" : "NU");
        }

        out.close();
    }

    static class DisjointSet {
        private final int[] father;
        private final int[] rank;
        private final int N;

        DisjointSet(int N){
            this.N = N;
            rank = new int[N + 1];
            father = new int[N + 1];

            for (int i = 1; i <= N; i++)
                initialize(i);
        }

        void initialize(int node){
            if (!(1 <= node && node <= N)) throw new AssertionError();
            father[node] = node;
            rank[node] = 1;
        }

        int find(int node){
            if (!(1 <= node && node <= N)) throw new AssertionError();

            if (father[node] == node)
                return node;
            else
                return father[node] = find(father[node]);
        }

        void union(int x, int y){
            x = find(x);
            y = find(y);

            if (x != y){
                if (rank[x] < rank[y])
                    father[x] = y;
                else
                    father[y] = x;

                if (rank[x] == rank[y])
                    rank[x]++;
            }
        }

        boolean connected(int x, int y){
            return find(x) == find(y);
        }
    }


    static class InputReader{
        private BufferedReader reader;
        private StringTokenizer tokenizer;

        InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 65536);
            tokenizer = null;
        }

        private String nextToken() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()){
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                }
                catch (IOException e){
                    throw new RuntimeException(e);
                }
            }

            return  tokenizer.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(nextToken());
        }

        String nextString(){
            return nextToken();
        }
    }
}