Cod sursa(job #3238597)

Utilizator GabrielPopescu21Silitra Gabriel - Ilie GabrielPopescu21 Data 27 iulie 2024 00:06:56
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
using namespace std;

const int MAX = 1e5;
int parent[MAX], rang[MAX];

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

    return parent[node] = FindRoot(parent[node]);
}

void Union(int firstNode, int secondNode)
{
    firstNode = FindRoot(firstNode);
    secondNode = FindRoot(secondNode);

    if (firstNode != secondNode)
    {
        if (rang[firstNode] < rang[secondNode])
            parent[firstNode] = secondNode;
        else if (rang[firstNode] > rang[secondNode])
            parent[secondNode] = firstNode;
        else
        {
            ++rang[firstNode];
            parent[secondNode] = firstNode;
        }
    }
}

int main()
{
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");
    int n, q;
    cin >> n >> q;

    for (int i = 1; i <= n; ++i)
        parent[i] = i;

    while (q--)
    {
        int type, x, y;
        cin >> type >> x >> y;
        if (type == 1)
            SetUnion(x, y);
        else
        {
            if (FindRoot(x) == FindRoot(y))
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }

    return 0;
}