Cod sursa(job #2868083)

Utilizator acostin643costin andrei acostin643 Data 10 martie 2022 18:39:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>

using namespace std;

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

const int NMAX = 100000;
int t[NMAX + 5], h[NMAX + 5];

int boss(int x)
{
    while(x != t[x])
        x = t[x];
    return x;
}

void unite(int x, int y)
{
    x = boss(x);
    y = boss(y);

    if(x == y)
        return;
    if(h[x] < h[y])
        t[x] = y;
    else if(h[x] > h[y])
        t[y] = x;
    else
        t[x] = y, h[y]++;
}

bool solve(int x, int y)
{
    return boss(x) == boss(y);
}

int main()
{
    int n, m, cod, x, y;
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        t[i] = i;
    }
    for(int i = 1; i <= m; i++)
    {
        fin >> cod >> x >> y;
        if(cod == 1)
        {
            unite(x, y);
        }
        if(cod == 2)
        {
            if(solve(x, y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}