Cod sursa(job #3344450)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 1 martie 2026 23:33:59
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 100005;
int parent[MAX];

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

int FindRoot(int x)
{
    int rad = x;
    while (parent[rad] != 0)
        rad = parent[rad];

    while (rad != x)
    {
        int y = parent[x];
        parent[x] = rad;
        x = y;
    }

    return rad;
}

int main()
{
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        int op, x, y;
        cin >> op >> x >> y;

        int xx = FindRoot(x);
        int yy = FindRoot(y);

        if (op == 1)
        {
            if (xx != yy)
                Union(xx, yy);
        }
        else
        {
            if (xx == yy)
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }

    return 0;
}