Cod sursa(job #2168669)

Utilizator LittleWhoFeraru Mihail LittleWho Data 14 martie 2018 11:55:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = 100001;
int n, m, k;
int roots[nmax];
int ranks[nmax];

void init_union_find() {
    for (int i = 1; i <= n; i++) roots[i] = i;
}

int find(int x) {
    int y, t;
    y = x;

    while (x != roots[x]) x = roots[x];
    while (y != x) {
        t = roots[y];
        roots[y] = x;
        y = t;
    }
    return x;
}

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

    if (ranks[x] > ranks[y]) {
        ranks[x] += ranks[y];
        roots[y] = x;
    } else if (ranks[x] == ranks[y]) {
        ranks[x]++;
        roots[y] = x;
    } else {
        ranks[y] += ranks[x];
        roots[x] = y;
    }
}

bool check(int x, int y) {
    return find(x) == find(y);
}

int main() {
    freopen("carici.in", "r", stdin);

    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    scanf("%d%d", &n, &m);
    init_union_find();
    while (m--) {
        int x, y, z;
        scanf("%d%d%d", &z, &x, &y);
        if (z == 1) {
            unite(x, y);
        } else {
            if (check(x, y)) {
                cout << "DA\n";
            } else {
                cout << "NU\n";
            }
        }
    }

    return 0;
}