Cod sursa(job #2238574)

Utilizator AndreiVisoiuAndrei Visoiu AndreiVisoiu Data 6 septembrie 2018 13:35:50
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.76 kb
#include <cstdio>

using namespace std;

const int NMAX = 100001;
int h[NMAX], p[NMAX],
    n;

int find_c(int x) {
    if(p[x] == 0)
        return x;
    return p[x] = find_c(p[x]);
}

void union_p(int x, int y) {
    if(h[x] > h[y]) p[y] = x;
    else p[x] = y;

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

int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    int m, cod, x, y;
    scanf("%i %i", &n, &m);
    for(int i = 1; i <= n; i++)
        h[i] = 1;

    while(m--) {
        scanf("%i %i %i", &cod, &x, &y);
        if(cod == 2) {
            if(find_c(x) == find_c(y)) printf("DA\n");
            else printf("NU\n");
        } else
            union_p(find_c(x), find_c(y));
    }
    return 0;
}