Cod sursa(job #3173726)

Utilizator TonyyAntonie Danoiu Tonyy Data 23 noiembrie 2023 16:41:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <bits/stdc++.h>
using namespace std;

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

const int Max = 100001;
int n, m, x, y, cod, tata[Max], rang[Max];

int find_set(int nod)
{
    if (tata[nod] == nod)
        return nod;
    return tata[nod] = find_set(tata[nod]);
}

void union_sets(int nod1, int nod2)
{
    nod1 = find_set(nod1);
    nod2 = find_set(nod2);
    if (nod1 == nod2)
        return;
    if (rang[nod1] < rang[nod2])
        swap(nod1, nod2);
    if (rang[nod1] == rang[nod2])
        ++rang[nod1];
    tata[nod2] = nod1;
}

int main()
{
    fin >> n >> m;
    for (int i = 1 ; i <= n ; ++i)
    {
        tata[i] = i;
        rang[i] = 1;
    }
    for (int i = 1 ; i <= m ; ++i)
    {
        fin >> cod >> x >> y;
        if (cod == 1)
            union_sets(x, y);
        else if (find_set(x) == find_set(y))
            fout << "DA \n";
        else
            fout << "NU \n";
    }
    fin.close();
    fout.close();
    return 0;
}