Cod sursa(job #3372311)

Utilizator Razvan23Razvan Mosanu Razvan23 Data 3 noiembrie 2026 10:04:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>
using namespace std;

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

vector<int> T, S;
int n, m;

int Find(int x)
{
    int aux, rad;
    rad = x;
    while(T[rad] != rad)
        rad = T[rad];
    while(rad != x)
    {
        aux = T[x];
        T[x] = rad;
        x = aux;
    }
    return rad;
}

void Union(int x, int y)
{
    x = Find(x);
    y = Find(y);
    if(x != y)
    {
        if(S[x] < S[y]) swap(x, y);
        T[y] = x;
        S[x] += S[y];
    }
}

int main()
{
    int t, x, y, i;
    fin >> n >> m;
    T.resize(n + 1);
    S.resize(n + 1);
    for(i = 1; i <= n; i++)
    {
        T[i] = i;
        S[i] = 0;
    }
    for(i = 1; i <= m; i++)
    {
        fin >> t >> x >> y;
        if(t == 1) Union(x, y);
        else 
        {
            x = Find(x);
            y = Find(y);
            if(x == y) fout << "DA\n";
            else fout << "NU\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}