Cod sursa(job #2870983)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 12 martie 2022 19:23:45
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
using namespace std;

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

int n, m;
int fathers[100005];
int depth[100005];

int FindRoot(int node)
{
    if (node == fathers[node])
    {
        return node;
    }
    return fathers[node] = FindRoot(fathers[node]);
}

void Union(int a, int b)
{
    a = FindRoot(a);
    b = FindRoot(b);

    if (depth[a] == depth[b])
    {
        depth[a] += 1;
        fathers[b] = a;
    }
    else if (depth[a] < depth[b])
    {
        fathers[a] = b;
    }
    else
    {
        fathers[b] = a;
    }
}

int main()
{
    fin >> n >> m;

    for (int i = 1; i <= n; i++)
    {
        fathers[i] = i;
        depth[i] = 1;
    }

    for (int i = 0; i < m; i++)
    {
        int a, b, c;
        fin >> a >> b >> c;

        if (a == 1)
        {
            Union(b, c);
        }
        else
        {
            if (FindRoot(b) == FindRoot(c))
            {
                fout << "DA" << '\n';
            }
            else
            {
                fout << "NU" << '\n';
            }
        }
    }
}