Cod sursa(job #2739760)

Utilizator EusebiudistrugatorulLionel Messi Eusebiudistrugatorul Data 9 aprilie 2021 21:24:33
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int const N = 1e5 + 5;
vector<int> height(N), group(N); // height of a tree and the number of the set where is located each element
int n, m;

int find_root(int x) {
    int node = x;
    while (group[node] != node) {
        node = group[node];
    }
    //build a path between all nodes directly to the root 'node' in the tree
    //in this way we optimize the algorithm to not lose time in searching
    while (group[x] != x) {
        int aux = group[x];
        group[x] = node;
        x = aux;
    }
    return node;
}

void unite(int x, int y) {
    if (height[x] > height[y]) {
        group[y] = x;
    } else {
        group[x] = y;
    }
    if (height[x] == height[y]) {
        height[y]++;
    }
}

int main() {
    ios::sync_with_stdio(0), cin.tie(0);
    cin >> n >> m;
    for (int i = 1; i <= n; ++i) {
        height[i] = 1;
        group[i] = i;
    }
    for (int i = 1; i <= m; ++i) {
        int code, x, y;
        cin >> code >> x >> y;
        if (code == 1) {
            unite(find_root(x), find_root(y));
        } else {
            if (find_root(x) == find_root(y)) {
                cout << "DA\n";
            } else {
                cout << "NU\n";
            }
        }
    }
    return 0;
}