Cod sursa(job #2329519)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 26 ianuarie 2019 21:07:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#define MAXN 100010

using namespace std;

int father[MAXN], height[MAXN];

void doFather(int k, int &value) {
    if (k == father[k]) {
        value = k;
        return;
    }
    doFather(father[k], value);
    father[k] = value;
}

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

void reunite(int x, int y) {
    father[x] = father[y];
    if (height[x] == height[y])
        height[x] = height[y] = height[x] + 1;
}

void solve() {
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    int n, m, x, y, k;
    fin >> n >> m;
    initialize(n);
    for (int i = 0; i < m; i++) {
        fin >> k >> x >> y;
        if (k == 1) {
            doFather(x, x);
            doFather(y, y);
            reunite(x, y);
        }
        else {
            doFather(x, x);
            doFather(y, y);
            if (father[x] == father[y])
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
}

int main() {
    solve();
    return 0;
}