Cod sursa(job #1831443)

Utilizator Mr.DoomRaul Ignatus Mr.Doom Data 18 decembrie 2016 04:19:41
Problema Paduri de multimi disjuncte Scor 0
Compilator java Status done
Runda Arhiva educationala Marime 1.87 kb
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;

public class UnionFind
{
    private static int[] weight;
    private static int[] root;
    private static String content;

    public UnionFind(int n)
    {
        weight = new int[n + 1];
        root = new int[n + 1]; 
        Init(n);
    }

    private void Init(int n)
    {
        for (int index = 0; index < n; ++index)
        {
            weight[index] = 1;
            root[index] = index;
        }
    }

    private static void Union(int x, int y)
    {
        if (weight[x] > weight[y])
            root[y] = x;
        else
        {
            root[x] = y;
            if (weight[x] == weight[y])
                weight[y]++;
        }
    }

    private static int Find(int node)
    {
        if (node != root[node])
            root[node] = Find(root[node]);
        return root[node];
    }
    
    private static String Solve(Scanner is, int m)
    {
        content = "";
        for (int i = 0, op, x, y; i < m; ++i)
        {
            op = is.nextInt();
            x = is.nextInt();
            y = is.nextInt();
            switch (op)
            {
                case 1:
                    Union(Find(x), Find(y));
                    break;
                case 2:
                    content += (Find(x) == Find(y) ? "DA" : "NU") + '\n';
                    break;
            }
        }

        return content;
    }

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

        File outFile = new File("disjoint.out");
        FileOutputStream os = new FileOutputStream(outFile);

        if (!outFile.exists())
            outFile.createNewFile();

        int n = is.nextInt(), m = is.nextInt();
        new UnionFind(n);

        os.write(Solve(is, m).getBytes());
        os.flush();
        os.close();
    }
}