Cod sursa(job #2457291)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 17 septembrie 2019 09:27:05
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int MAXN = 1e5 + 10;

int height[MAXN], father[MAXN], n, m;

void findFather(int node, int &f) {
    if (node == father[node]) {
        f = father[node];
        return;
    }
    findFather(father[node], f);
    father[node] = f;
}

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

void reunite(int x, int y) {
    if (height[x] > height[y]) {
        int f;
        height[y] = height[x];
        findFather(x, f);
        father[y] = father[x];
    }
    else if (height[x] < height[y]) {
        int f;
        height[x] = height[y];
        findFather(y, f);
        father[x] = father[y];
    }
    else {
        int f;
        height[y] = ++height[x];
        findFather(x, f);
        father[y] = father[x];
    }
}

int main() {
    int x, y, c;
    fin >> n >> m;
    initialize();
    for (int i = 0; i < m; ++i) {
        fin >> c >> x >> y;
        if (c == 1)
            reunite(x, y);
        else {
            int f;
            findFather(x, f);
            findFather(y, f);
            if (father[x] == father[y])
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}