Cod sursa(job #3002842)

Utilizator PalcPalcu Stefan Palc Data 15 martie 2023 11:31:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, Q;
int t[100005];

void Union(int x, int y)
{
    t[y] = x;
}

int Find(int x)
{
    int rad = x, y;
    while (t[rad] != 0)
        rad = t[rad];
    while (x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

int main()
{
    int x, y, op;
    fin >> n >> Q;
    while (Q--)
    {
        fin >> op >> x >> y;
        if (op == 1)
        {
            x = Find(x);
            y = Find(y);
            Union(x, y);
        }
        else
        {
            x = Find(x);
            y = Find(y);
            if (x != y) fout << "NU\n";
            else fout << "DA\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}