Cod sursa(job #3273556)

Utilizator OanaAOana A OanaA Data 2 februarie 2025 17:01:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>

using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

int n, m, op;
int tata[100002], inaltime[100002];

int getRoot(int x)
{
    int root = x;
    while(root != tata[root])
        root = tata[root];
    while(x != tata[x])
    {
        int aux = tata[x];
        tata[x] = root;
        x = aux;
    }
    return root;
}

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

    if(inaltime[x] > inaltime[y])
    {
        tata[y] = x;
    }else if(inaltime[x] < inaltime[y])
    {
        tata[x]= y;
    }else{
        tata[x] = y;
        inaltime[y]++;
    }
}

int main()
{
    cin >> n >> m;
    for(int i=1; i<=n; ++i)
    {
        tata[i] = i;
        inaltime[i] = 1;
    }

    for(int i=1; i<=m; ++i)
    {
        int x, y;
        cin >> op >> x >> y;
        if(op == 1)
        {
            unite(x, y);
        }else{
            if(getRoot(x) == getRoot(y))
                cout << "DA" << "\n";
            else cout << "NU" << "\n";
        }
    }
    return 0;
}