Cod sursa(job #2737765)

Utilizator inwursuIanis-Vlad Ursu inwursu Data 5 aprilie 2021 08:14:24
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 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)
    {
        int temp = x;

        while (parent[temp] != 0)
        {
            temp = this->parent[temp];
        }

        int root = temp;

        temp = x;

        while (temp != root)
        {
            int next = this->parent[temp];
            this->parent[temp] = root;
            temp = next;
        }

        return root;
    }


    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;
            }
        }
    }
}