Cod sursa(job #1338097)

Utilizator DorelBarbuBarbu Dorel DorelBarbu Data 9 februarie 2015 19:40:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <cstdio>
using namespace std;

const int MAXN = 100000;

int N, M, rang[MAXN+1], father[MAXN+1];


int getSet(int x)
{
    int root, y;

    for(root = x; root != father[ root ]; root = father[ root ] );

    //y = root;

    y = x;

    while( y != father[ y ] )
    {
        int aux = father[ y ];
        father[ y ] = root;
        y = aux;
    }

    return root;
}

void initSets()
{
    for(int i = 1; i <= N; i++)
        father[ i ] = i;
}

void unionSets(int x, int y)
{
    if( rang[ x ] < rang[ y ] )
        father[ x ] = y;
    else father[ y ] = x;

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



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

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

    initSets();

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

        if( caz == 1 )
            unionSets( getSet( x ), getSet( y ) );
        else
        {
            if( getSet( x ) == getSet( y ) )
                printf("DA\n");
            else printf("NU\n");
        }
    }

    return 0;
}