Cod sursa(job #1976973)

Utilizator blatulInstitutul de Arta Gastronomica blatul Data 4 mai 2017 18:04:17
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
using namespace std;

#define NMAX 100002

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int tata[NMAX], pondere[NMAX];

inline void initDSU(const int N) {

    for (int i = 1; i <= N; ++i) {
        tata[i] = i;
        pondere[i] = 1;
    }
}

int getRoot(int x) {

    int root;

    for (root = x; root != tata[root]; root = tata[root]);

    int aux;

    while (x != tata[x]) {
        aux = tata[x];
        tata[x] = root;
        x = aux;
    }

    return root;
}

void unite(int x, int y) {

    x = getRoot(x);
    y = getRoot(y);

    if (x == y)
        return;

    if (pondere[x] > pondere[y])
        tata[y] = x;
    else
        tata[x] = y;

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

int main() {

    int N, M;

    fin >> N >> M;

    initDSU(N);

    int t, x, y;

    while (M--) {

        fin >> t >> x >> y;

        if (t == 1)
            unite(x, y);
        else
            fout << (getRoot(x) == getRoot(y) ? "DA\n" : "NU\n");
    }

    return 0;
}