Cod sursa(job #2457294)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 17 septembrie 2019 09:30:59
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 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) {
    int f;
    findFather(x, f);
    findFather(y, f);
    father[x] = father[y];
    if (height[x] == height[y])
        height[x] = ++height[y];
}

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;
}