Cod sursa(job #3343596)

Utilizator Costy2345Costi Dimian Costy2345 Data 27 februarie 2026 20:04:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 1e5 + 2;

int n, m, tata[NMAX], s[NMAX];

int root(int nod)
{
    int root = nod;
    while(tata[root] != root)
    {
        root = tata[root];
    }
    while(tata[nod] != root)
    {
        int temp = tata[nod];
        tata[nod] = root;
        nod = temp;
    }
    return root;
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        tata[i] = i;
        s[i] = 1;
    }
    for(int i = 1; i <= m; i++)
    {
        int op, x, y;
        fin >> op >> x >> y;
        if(op == 1)
        {
            if(s[x] <= s[y])
            {
                tata[root(x)] = root(y);
                s[y] += s[x];
            }
            else{
                tata[root(y)] = root(x);
                s[x] += s[y];
            }
        }   
        else if(op == 2)
        {
            fout << (root(x) == root(y) ? "DA" : "NU") << "\n";
        }
    }
    return 0;
}