Cod sursa(job #3252706)

Utilizator Giulian617Buzatu Giulian Giulian617 Data 30 octombrie 2024 18:52:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <bits/stdc++.h>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

struct DSU
{
    int n;
    vector<int> parent, rank;

    DSU() {}
    DSU(int _n) : n(_n)
    {
        parent.resize(n);
        rank.resize(n, 1);
        iota(parent.begin(), parent.end(), 0);
    }

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

    void UnionSets(int node1, int node2)
    {
        node1 = FindRoot(node1);
        node2 = FindRoot(node2);
        if (node1 == node2)
            return;
        if (rank[node1] < rank[node2])
            swap(node1, node2);
        if (rank[node1] == rank[node2])
            rank[node1]++;
        parent[node2] = node1;
    }
};

int main()
{
    ios_base::sync_with_stdio(false);
    f.tie(NULL);

    int n, m;
    f >> n >> m;
    DSU dsu(n);

    for (int i = 0; i < m; i++)
    {
        int op, x, y;
        f >> op >> x >> y;
        x--;
        y--;
        if (op == 1)
            dsu.UnionSets(x, y);
        else
            g << (dsu.FindRoot(x) == dsu.FindRoot(y) ? "DA" : "NU") << '\n';
    }
    return 0;
}