Cod sursa(job #2809826)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 27 noiembrie 2021 17:57:16
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;


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

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

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

void SetUnion(int x, int y)
{
    int rootX = FindRoot(x);
    int rootY = FindRoot(y);

    if (depth[rootX] > depth[rootY])
    {
        // rootX
        parent[rootY] = rootX;
    }
    else
    {
        // rootY
        if (depth[rootX] == depth[rootY])
        {
            depth[rootX]++;
        }
        parent[rootX] = rootY;
    }
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i < n; i++)
    {
        parent[i] = i;
    }
    while (m--)
    {
        int t, x, y;
        fin >> t >> x >> y;

        if (t == 1)
        {
            SetUnion(x, y);
        }
        else
        {
            if (FindRoot(x) == FindRoot(y))
            {
                fout << "DA" << '\n';
            }
            else
            {
                fout << "NU" << '\n';
            }
        }
    }
}