Cod sursa(job #653662)

Utilizator SimeneSimene Robert Simene Data 28 decembrie 2011 16:56:37
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.05 kb
#include <stdio.h>
#define NMAX 100020
int ARB[NMAX], RANG[NMAX];
int N, M;

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

for (R = x; ARB[R] != R; R = ARB[R]);
    for (; ARB[x] != x;)
        {
            y = ARB[x];
            ARB[x] = R;
            x = y;
        }
return R;
}
void unire(int x, int y)
{
if (RANG[x] > RANG[y])
    ARB[y] = x;
    else ARB[x] = y;
if (RANG[x] == RANG[y])
    RANG[y]++;
}
int main()
{
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
scanf("%d %d ", &N, &M);
int i, x, y, cd;

for (i = 1; i <= N; i++)
    {
    ARB[i] = i;
    RANG[i] = 1;
    }

for (i = 1; i <= M; i++)
    {
    scanf("%d %d %d", &cd, &x, &y);
    if (cd == 2){
    if (caut(x) == caut(y))
        printf("DA\n");
        else printf("NU\n");

                }
        else
            {
            if (caut(x) == caut(y))
                {
                fprintf(stderr,"%d ", i);
                return 0;
                }
            unire(caut(x), caut(y));
            }
    }
return 0;
}