Cod sursa(job #2629246)

Utilizator doyouhavethetimeStanculescu Gabriel doyouhavethetime Data 19 iunie 2020 17:20:47
Problema Paduri de multimi disjuncte Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <ctype.h>
#include <stdio.h>
#define N 100000

#ifdef __unix__
#define getchar getchar_unlocked
#define putchar putchar_unlocked
#endif // __unix__

int read () {
    int ch;
    while (!isdigit(ch=getchar()));

    int ans=0;
    do
        ans = (ans<<3) + (ans<<1) + ch - '0';
    while (isdigit(ch=getchar()));

    return ans;
}

int parent[N+1], children[N+1];
int _find (int x) {
    if (!parent[x])
        return x;
    return parent[x]=_find(parent[x]);
}

void _union (int x, int y) {
    x=_find(x);
    y=_find(y);

    if (x!=y)
        if (children[x] > children[y]) {
            parent[x] = y;
            children[y] += children[x];
        }
        else {
            parent[y] = x;
            children[x] += children[y];
        }
}

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

    int n, m;
    n=read(), m=read();

    int i, j, k;
    for (; m; m--) {
        k=read();
        i=read();
        j=read();
        if (k==1)
            _union(i, j);
        else
            puts(_find(i)==_find(j)?"DA":"NU");
    }
    return 0;
}