Cod sursa(job #1878796)

Utilizator savigunFeleaga Dragos-George savigun Data 14 februarie 2017 14:31:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
using namespace std;

int father[100001], height[100001];

int get_root(int x) {
    if (father[x] == x)
        return x;
    return get_root(father[x]);
}

void join(int x, int y) {
    int rootX = get_root(x);
    int rootY = get_root(y);

    if (height[rootX] >= height[rootY]) {
        father[rootY] = rootX;
        if (height[rootX] == height[rootY])
            height[rootX]++;
    } else {
        father[rootX] = rootY;
    }
}


int main() {
    ifstream cin("disjoint.in");
    ofstream cout("disjoint.out");

    int n, m, x, y, o;
    cin >> n >> m;

    for (int i = 1; i <= n; ++i) {
        father[i] = i;
        height[i] = 1;
    }

    for (int i = 1; i <= m; ++i) {
        cin >> o >> x >> y;
        if (o == 1) {
            join(x, y);
        } else {
            if (get_root(x) == get_root(y)) {
                cout << "DA" << '\n';
            } else {
                cout << "NU" << '\n';
            }
        }
    }


    return 0;
}