Cod sursa(job #3268018)

Utilizator catalinmarincatalinmarin catalinmarin Data 13 ianuarie 2025 15:29:29
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int root[int(1e5) + 5];
int depth[int(1e5) + 5];
int sz[int(1e5) + 5];

int find_root(int x){
    if (root[x] == x)
        return x;
    root[x] = find_root(root[x]);
    return root[x];
}
void merge(int x, int y){

    if (depth[x] < depth[y]){
        swap(x, y);
    }

    root[y] = root[x];
    sz[x] += sz[y];
    depth[x] = max(depth[x], depth[y] + 1);
}

int main(){

    int n, m;
    fin >> n >> m;

    for (int i = 1; i <= n; i++) {
        root[i] = i;
        depth[i] = 1;
    }

    for (int op = 1; op <= m; op++){

        int cod, x, y;
        fin >> cod >> x >> y;
        int root_x = find_root(x);
        int root_y = find_root(y);
        if (cod == 1){
            if (root[x] != root[y])
                merge(root[x], root[y]);
        } else {
            if (root[x] == root[y])
                fout << "DA" << '\n';
            else
                fout << "NU" << '\n';
        }

    }

    return 0;
}