Cod sursa(job #863028)

Utilizator Catah15Catalin Haidau Catah15 Data 23 ianuarie 2013 10:37:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <cstdio>
#include <algorithm>

using namespace std;

#define maxN 100010

int tata[maxN], H[maxN];


inline int root (int x)
{
    int R = 0;
    for (R = x; R != tata[R]; R = tata[R]);
    for (int y; x != R; y = x, x = tata[x], tata[y] = R);

    return R;
}


void unite (int x, int y)
{
    int rx = root (x), ry = root (y);

    if (H[rx] < H[ry]) tata[rx] = ry;
    else if (H[rx] > H[ry]) tata[ry] = rx;
    else ++ H[rx], tata[ry] = rx;
}


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

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

    for (int i = 1; i <= N; ++ i) tata[i] = i;

    while (M --)
    {
        int cod, x, y;
        scanf ("%d %d %d", &cod, &x, &y);

        if (cod == 1)
        {
            if (root (x) != root (y)) unite (x, y);
        }
        else
        {
            if (root (x) == root(y)) printf ("DA\n");
            else printf ("NU\n");
        }
    }

    return 0;
}