Cod sursa(job #2865226)

Utilizator Mihai7218Bratu Mihai-Alexandru Mihai7218 Data 8 martie 2022 17:13:19
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n, m, i, j, t, op, roots[100001], sizefor[100001], x, y;
int root (int a)
{
    int as = a;
    while (a != roots[a])
        a = roots[a];
    roots[as] = a;
    return a;
}
bool join (int x, int y)
{
    x = root(x);
    y = root(y);
    if (sizefor[x] > sizefor[y]) swap(x, y);
    roots[x] = y;
    sizefor[y] += sizefor[x];
}
int main()
{
    fin >> n >> m;
    for (i = 1; i<= n; i++)
        roots[i] = i, sizefor[i] = 1;
    for (t = 1; t <= m; t++)
    {
        fin >> op >> x >> y;
        if (op == 1)
            join(x, y);
        else if (op == 2)
        {
            if (root(x) == root(y))
                fout << "DA\n";
            else fout << "NU\n";
        }
    }
    return 0;
}