Cod sursa(job #3375064)

Utilizator Mihai09Mihai Arteni Mihai09 Data 10 noiembrie 2026 09:43:47
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,t[100010];

int get_root(int x)
{
    int aux = x;
    while(t[x] > 0)
    {
        x = t[x];
    }
    int root = x;
    x = aux;
    while(x != root)
    {
        aux = x;
        x = t[x];
        t[aux] = root;
    }
    return root;
}

bool query(int x,int y)
{
    return get_root(x) == get_root(y);
}

void join(int x,int y)
{
    if(!query(x,y))
    {
        x = get_root(x);
        y = get_root(y);
        if(t[x] < t[y])
        {
            t[y]+=t[x];
            t[y] = x;
        }
        else
        {
            t[y]+=t[x];
            t[x] = y;
        }
    }

}

int main()
{
    fin >>n >>m;
    for(int i = 1;i <= n;i++)
    {
        t[i] = -1;
    }
    while(m--)
    {
        int type,x,y;
        fin >>type >>x >>y;
        if(type == 1)
        {
            join(x,y);
        }
        else
        {
            if(query(x,y))
            {
                fout <<"DA\n";
            }
            else
            {
                fout <<"NU\n";
            }
        }
    }
    return 0;
}