Cod sursa(job #1463137)

Utilizator BaweeLazar Vlad Bawee Data 20 iulie 2015 11:28:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <cstdio>

#define NMAX 100020

int TT[NMAX], RG[NMAX];
int N, M;

int find(int x)
{
    int R, y;

    for (R = x; TT[R] != R; R = TT[R]);

    while (TT[x] != x)
    {
        y = TT[x];
        TT[x] = R;
        x = y;
    }
    return R;
}

void unite(int x, int y)
{
    if (RG[x] > RG[y])
        TT[y] = x;
    else TT[x] = y;

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

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

    scanf("%d %d ", &N, &M);

    int i, x, y, cond;

    for (i = 1; i <= N; i++)
    {
        TT[i] = i;
        RG[i] = 1;
    }

    for (i = 1; i <= M; i++)
    {
        scanf("%d %d %d", &cond, &x, &y);

        if (cond == 2){
            if (find(x) == find(y)) printf("DA\n");
                else printf("NU\n");
        }
            else
                unite(find(x), find(y));
    }


    return 0;
}