Cod sursa(job #2418131)

Utilizator AlexNeaguAlexandru AlexNeagu Data 3 mai 2019 19:19:59
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#define nmax 100005

using namespace std;

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

int t[nmax], rg[nmax], n, m, x, y, p;

int cautare (int x)
{
    int R = x;
    while (R != t[R])
        R = t[R];

    while (t[x] != x)
    {
        int aux = t[x];
        t[x] = R;
        x = aux;
    }

    return R;
}
void unire(int x, int y)
{
    if (rg[x] >= rg[y])
        t[y] = x;
    else t[x] = y;

    if (rg[x] == rg[y])
        rg[x] ++;
}
int main()
{
    ios_base::sync_with_stdio(false);

    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        t[i] = i;
        rg[i] = 1;
    }

    for (int i = 1; i <= m; i++)
    {
        fin >> p >> x >> y;
        int v1 = cautare (x);
        int v2 = cautare (y);
        if (p == 1)
        unire (v1, v2);
        if (p == 2)
        (v1 == v2) ? fout << "DA\n" : fout << "NU\n";
    }
    return 0;
}