Cod sursa(job #2611940)

Utilizator matthriscuMatt . matthriscu Data 7 mai 2020 21:12:48
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <cstdio>

int t[100005], rang[100005];

int root(int x) {
    int r, y;
    for(r = x ; t[r] != r; r = t[r]);
 
    while(x != t[x]) {
        y = t[x];
        t[x] = r;
        x = y;
    }
    return r;
}

void join(int x, int y) {
    int rootX = root(x), rootY = root(y);
    if(rang[x] > rang[y])
        t[rootY] = rootX;
    else {
        t[rootX] = rootY;
        if(rang[x] == rang[y])
            ++rang[y];
    }    
}

int main() {
    int n, m, i, c, x, y;
    scanf("%d%d", &n, &m);
    for(i = 1; i <= n; ++i)
        t[i] = i;
    for(i = 1; i <= m; ++i) {
        scanf("%d%d%d", &c, &x, &y);
        if(c == 1)
            join(x, y);
        else
            if(root(x) == root(y))
                printf("DA\n");
            else
                printf("NU\n");            
    }
}