Cod sursa(job #2737767)

Utilizator inwursuIanis-Vlad Ursu inwursu Data 5 aprilie 2021 08:24:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
// disjoint.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <fstream>

using namespace std;

const int N_MAX = 100000 + 1;

int parent[N_MAX];
int cardinal[N_MAX];



int find_root(int x)
{
    if (parent[x] == 0)
    {
        return x;
    }

    return parent[x] = find_root(parent[x]);
}


void merge_sets(int x, int y)
{
    int root_x = find_root(x);
    int root_y = find_root(y);

    if (root_x == root_y) return;

    if (cardinal[root_x] < cardinal[root_y])
    {
        swap(root_x, root_y);
    }

    parent[root_y] = root_x;
    cardinal[root_x] += cardinal[root_y];
    cardinal[root_y] = 0;
}




int main()
{
    ifstream fin{ "disjoint.in" };
    ofstream fout{ "disjoint.out" };

    int N, Q;
    fin >> N >> Q;

    for (int i = 1; i <= Q; ++i)
    {
        int x, y, op;

        fin >> op >> x >> y;

        if (op == 1)
        {
           merge_sets(x, y);
        }
        else
        {
            if (find_root(x) == find_root(y))
            {
                fout << "DA\n";
            }
            else
            {
                fout << "NU\n";
            }
        }
    }
}