Cod sursa(job #2026428)

Utilizator FrequeAlex Iordachescu Freque Data 24 septembrie 2017 13:53:37
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <iostream>

using namespace std;

const int NMAX = 100000 + 5;

int n, m;
int root[NMAX], rang[NMAX];

void read()
{
    cin >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        root[i] = i;
        rang[i] = 1;
    }
}

int find_root(int x)
{
    int i;
    for (i = x; i != root[i]; i = root[i]);

    while (x != root[x])
    {
        int y = root[x];
        root[x] = i;
        x = y;
    }

    return i;
}

void unite(int x, int y)
{
    if (rang[x] > rang[y])
    {
        rang[x] += rang[y];
        root[y] = x;
    }
    else
    {
        rang[y] += rang[x];
        root[x] = y;
    }
}

int main()
{
    int cod, x, y;
    read();

    for (int i = 1; i <= m; ++i)
    {
        cin >> cod >> x >> y;
        if (cod == 1)
        {
            if (find_root(x) != find_root(y))
                unite(find_root(x), find_root(y));
        }
        else
        {
            if (find_root(x) == find_root(y))
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }

    return 0;
}