Cod sursa(job #1771306)

Utilizator gabor.vlad13lil pump gabor.vlad13 Data 5 octombrie 2016 14:16:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <cstring>
#include <cstdio>
#include <iostream>

using namespace std;

int n, m;
int t[100001];
int a[100001];



int radacina(int x)
{
    int aux = x, tmp;
    while(t[x] != x)
    {
        x = t[x];
    }

    while(t[aux] != aux)
    {
        tmp = aux;
        aux = t[aux];
        t[tmp] = x;
    }
    return x;
}

void initializare()
{
    for (int i=1; i<=100000; i++)
        t[i] = i;
}

void read()
{
    int operatie, x, y;
    scanf("%d %d\n", &n, &m);
    for (int i=1; i<=m; i++)
    {
        scanf("%d %d %d\n", &operatie, &x, &y);
        if (operatie == 1)
        {
            if (a[x] == a[y])
            {
                t[radacina(y)] = radacina(x);
                a[x]++;
            }
            else if (a[x] < a[y])
            {
                t[radacina(x)] = radacina(y);
            }

            else if (a[x] > a[y])
            {
                t[radacina(y)] = radacina(x);
            }


        }
        else if (radacina(x) == radacina(y))
            cout<<"DA\n";
        else
            cout<<"NU\n";
    }
}

int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    initializare();
    read();
    return 0;
}