Cod sursa(job #2358607)

Utilizator LittleWhoFeraru Mihail LittleWho Data 28 februarie 2019 10:39:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

using namespace std;

typedef unsigned long long ull;
typedef signed long long ll;
typedef unsigned int uint;
const int nmax = 100005;

uint n, m;
uint ranks[nmax], roots[nmax];


uint find(uint x) {
    uint R;
    for (R = x; R != roots[R]; R = roots[R]) ;

    uint y = x;
    uint tmp;
    while (y != roots[y]) {
        tmp = roots[y];
        roots[y] = R;
        y = tmp;
    }

    return R;
}

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


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

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

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

    scanf("%u%u", &n, &m);

    for (uint i = 1; i <= n; i++) {
        roots[i] = i;
        ranks[i] = 1;
    }

    for (uint i = 0, op, x, y; i < m; i++) {
        scanf("%u%u%u", &op, &x, &y);

        if (op == 1) unite(x, y);
        else {
            if (check(x, y)) {
                cout << "DA\n";
            } else {
                cout << "NU\n";
            }
        }
    }
}