Cod sursa(job #2060012)

Utilizator papinub2Papa Valentin papinub2 Data 7 noiembrie 2017 20:04:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>

using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

int n, m, x, y, op;
int tata[100005], lg[100005];

int cautare (int x)
{
    int copie = x, aux;

    while (tata[copie] != 0)
        copie = tata[copie];

    while (tata[x] != 0)
    {
        aux = tata[x];
        tata[x] = copie;
        x = aux;
    }

    return copie;
}

void unire (int x, int y)
{
    if (lg[x] > lg[y])
        tata[y] = x;
    else
        tata[x] = y;

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

int main()
{
    in >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        in >> op >> x >> y;

        if (op == 1)
            unire (cautare(x), cautare(y));

        else

        {
            if (cautare(x) == cautare(y))
                out << "DA" << '\n';
            else
                out << "NU" << '\n';
        }
    }

    return 0;
}