Cod sursa(job #3300340)

Utilizator andrei_nAndrei Nicolae andrei_n Data 14 iunie 2025 20:32:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");

int tata[100005];
int heights[100005];

int radacina(int nod)
{
    int root = nod;
    while (root != tata[root])
        root = tata[root];
    while (nod != root)
    {
        int nextNode = tata[nod];
        tata[nod] = root;
        nod = nextNode;
    }
    return root;
}

void uneste(int x, int y)
{
    int rootX = radacina(x);
    int rootY = radacina(y);

    if (heights[rootX] < heights[rootY])
        tata[rootX] = rootY;
    else if (heights[rootX] > heights[rootY])
        tata[rootY] = rootX;
    else
        tata[rootX] = rootY;
        heights[rootY]++;
}

int main()
{
    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        tata[i] = i;
        heights[i] = 1;
    }
    for (int i = 0; i < m; i++)
    {
        int op, x, y;
        fin >> op >> x >> y;
        if (op == 1)
            uneste(x, y);
        else
            if (radacina(x) == radacina(y))
                fout << "DA" << '\n';
            else
                fout << "NU" << '\n';

    }
    return 0;
}