Cod sursa(job #2737766)

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

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

class DSU 
{
private:
    int N;
    vector<int> parent;
    vector<int> cardinal;


public:
    DSU(int N) : N {N}
    {
        parent.resize(N + 1, 0);
        cardinal.resize(N + 1, 1);
    }


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

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

        return parent[x];
    }


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

        if (root_x == root_y) return;

        if (this->cardinal.at(root_x) < this->cardinal.at(root_y))
        {
            swap(root_x, root_y);
        }

        this->parent[root_y] = root_x;
        this->cardinal[root_x] += this->cardinal[root_y];
        this->cardinal[root_y] = 0;
    }
};



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

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

    DSU dsu(N);

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

        fin >> op >> x >> y;

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