Cod sursa(job #1024244)

Utilizator supermitelArdelean Razvan Mitel supermitel Data 8 noiembrie 2013 14:43:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.07 kb
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <cstring>
#define NMAX 100010

using namespace std;

int par[NMAX], h[NMAX];
int n;

void setare()
{
    int i;
    for(i = 0; i <= n; i++)
        par[i] = -1;
}

int getroot(int x)
{
    if(par[x] == -1)
        return x;
    par[x] = getroot(par[x]);
    h[x] = h[par[x]] + 1;
    return par[x];
}

void reuniune(int x, int y)
{
    int rx, ry;
    rx = getroot(x);
    ry = getroot(y);
    if(rx == ry)
        return;
    if(h[rx] < h[ry])
        swap(rx, ry);
    par[ry] = rx;
    h[rx] ++;
}

void verif(int x, int y)
{
    if(getroot(x) == getroot(y))
        printf("DA\n");
    else printf("NU\n");
}

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

    int T, x, y, z;
    scanf("%d%d", &n, &T);
    setare();
    while(T--)
    {
        scanf("%d%d%d", &x, &y, &z);
        if(x == 1)
            reuniune(y, z);
        else verif(y, z);
    }

    return 0;
}