Cod sursa(job #2376210)

Utilizator SqueekDanielTodasca Daniel SqueekDaniel Data 8 martie 2019 14:09:41
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>

#define MAXN 100005

int N, M;
int Root[MAXN], Rang[MAXN];

int Find(int X) {
    int root = X;
    while (Root[root] != root)
        root = Root[root];

    int aux;
    while (Root[X] != X)
        aux = Root[X], Root[X] = root, X = aux;
    return root;
}

void Union(int X, int Y) {
    if (X == Y) return;
    if (Rang[X] == Rang[Y])
        ++ Rang[X], Root[Y] = X;
    else if (Rang[X] < Rang[Y])
        Root[X] = Y;
    else
        Root[Y] = X;
}

std::ifstream In ("disjoint.in");
std::ofstream Out("disjoint.out");

void Citire() {
    In >> N >> M;
}

void Rezolvare() {
    for (int i=1; i<=N; ++i)
        Root[i] = i;
    int type, X, Y;
    while (M--) {
        In >> type >> X >> Y;
        if (type == 1)
            Union(Find(X), Find(Y));
        else
            Out << (Find(X) == Find(Y) ? "DA\n" : "NU\n");
    }
}

int main()
{
    Citire();
    Rezolvare();

    return 0;
}