Cod sursa(job #3142038)

Utilizator Traian_7109Traian Mihai Danciu Traian_7109 Data 18 iulie 2023 15:20:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

struct DSU {
    vector<int> root, cardinal;
    int n;
    
    void init(const int &new_n) {
        n = new_n;
        root.resize(n+1), cardinal.resize(n+1);
        for (int i = 1; i <= n; i++)
            root[i] = i, cardinal[i] = 1;
    }
    
    int find_root(const int &node) {
        if (root[node] == node)
            return node;
        return find_root(root[node]);
    }
    
    void unite(int root1, int root2) {
        if (root1 == root2)
            return;
        if (cardinal[root1] < cardinal[root2])
            swap(root1, root2);
        cardinal[root1] += cardinal[root2];
        cardinal[root2] = 0;
        root[root2] = root1;
    }
};

DSU dsu;

int main() {
    ios_base :: sync_with_stdio(false);
    fin.tie(nullptr), fout.tie(nullptr);
    
    int n, m;
    fin>>n>>m;
    dsu.init(n);
    while (m--) {
        int task, x, y;
        fin>>task>>x>>y;
        int root_x = dsu.find_root(x), root_y = dsu.find_root(y);
        if (task == 1)
            dsu.unite(root_x, root_y);
        else
            if (root_x == root_y)
                fout<<"DA\n";
            else
                fout<<"NU\n";
    }
    return 0;
}