Cod sursa(job #2376528)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 8 martie 2019 16:10:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#define NMAX 100010

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

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

int find(int x) {
    int root = x;
    while (father[root])
        root = father[root];

    int aux;
    while (father[x]) {
        aux = father[x];
        father[x] = root;
        x = aux;
    }
    return root;
}

void unite(int rootX, int rootY) {
    if (height[rootX] < height[rootY])
        father[rootX] = rootY;
    else {
        father[rootY] = rootX;
        if (height[rootX] == height[rootY])
            height[rootX]++;
    }
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, z;
        fin >> x >> y >> z;

        if (x == 1)
            unite(find(y), find(z));
        else
            fout << (find(y) == find(z) ? "DA\n" : "NU\n");
    }

    fout.close();
    return 0;
}