Cod sursa(job #3261991)

Utilizator winemomComan Erin winemom Data 8 decembrie 2024 09:38:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
#define nMax 100005

int tat[nMax], nr[nMax], n;

int rad(int x)
{
    if(tat[x] == 0)
        return x;
    tat[x] = rad(tat[x]);
    return tat[x];
}

void Union(int x, int y)
{
    int rx = rad(x);
    int ry = rad(y);
    if(nr[rx] < nr[ry])
        swap(rx, ry);

    tat[ry] = rx;
    nr[rx] += nr[ry];
}

bool Find(int x, int y)
{
    int rx = rad(x);
    int ry = rad(y);
    return rx == ry;
}

int main()
{
    for(int i=0; i<=nMax; i++)
        nr[i] = 1;
    short operatie;
    int x, y;
    int q;
    f >> n >> q;
    while(q--)
    {
        f >> operatie >> x >> y;
        if(operatie == 1)
            Union(x, y);
        else
            if(operatie == 2)
        {
            if(Find(x, y))
                g << "DA\n";
            else
                g << "NU\n";
        }
    }
}