Cod sursa(job #3181059)

Utilizator Patrik06Patrik Patrik06 Data 6 decembrie 2023 13:14:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <iostream>
#include <fstream>

using namespace std;
int tata[100001], n, m, x, y, rx, ry, t;
int rad(int x)
{
    while(tata[x] > 0)
        x = tata[x];

    return x;
}

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

    cin >> n >> m;
    for(int i = 1; i <= n; i++)
        tata[i] = -1;

    for(int i = 1; i <= m; i++)
    {
        cin >> t >> x >> y;
        if(t == 1)
        {
            rx = rad(x);
            ry = rad(y);
            if(rx != ry)
            {
                if(tata[rx] < tata[ry]) /// rx devine rad arb unificat
                {
                    tata[rx] += tata[ry];
                    tata[ry] = rx;
                }
                else
                {
                    tata[ry] += tata[rx]; /// ry devine rad arb unificat
                    tata[rx] = ry;
                }
            }
        }
        else
        {
            rx = rad(x);
            ry = rad(y);
            if(rx == ry)
                cout << "DA"<< '\n';
            else
                cout << "NU" << '\n';
        }
    }
    return 0;
}