Cod sursa(job #2354824)

Utilizator TudoseSanzianaTudose Sanziana TudoseSanziana Data 25 februarie 2019 16:54:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>
using namespace std;

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

const int N_MAX = 100000;

int n, m, cod, x, y;

int daddy[N_MAX + 2], depth[N_MAX + 2];

int root(int arg) {
    while(arg != daddy[arg])
        arg = daddy[arg];

    return arg;
}

void join(int rootX, int rootY) {
    if(depth[rootX] > depth[rootY])
        daddy[rootY] = rootX;

    if(depth[rootY] > depth[rootX])
        daddy[rootX] = rootY;

    if(depth[rootX] == depth[rootY]) {
        daddy[rootX] = rootY;
        depth[rootY]++;
    }
}

int main() {
    in >> n >> m;

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

    while(m--) {
        in >> cod >> x >> y;
        if(cod == 1)
            join(root(x), root(y));
        else
            out << (root(x) == root(y) ? "DA" : "NU") << '\n';
    }

    return 0;
}