Cod sursa(job #2677008)

Utilizator robeert.77Chirica Robert robeert.77 Data 25 noiembrie 2020 17:37:21
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int n, m, tree[100005], level[100005];

int root(int node) {
    if (node == tree[node])
        return node;
    return root(tree[node]);
}

void nodesToRoot(int node, int root) {
    if (node == root)
        return;
    nodesToRoot(tree[node], root);
    tree[node] = root;
}

int main() {
    fin.tie(0);
    fout.tie(0);
    ios::sync_with_stdio(0);
    fin >> n >> m;
    for (int i = 1; i <= n; i++) {
        tree[i] = i;
        level[i] = 1;
    }
    int operation, a, b;
    for (int i = 0; i < m; i++) {
        fin >> operation >> a >> b;
        int rootA = root(a);
        int rootB = root(b);
        if (operation == 1) {
            if (rootA > rootB)
                swap(rootA, rootB);
            tree[rootA] = rootB;
            level[rootB] = max(level[rootA] + 1, level[rootB]);
        }
        else if (rootA == rootB)
            fout << "DA\n";
        else
            fout << "NU\n";
        nodesToRoot(a, rootA);
        nodesToRoot(b, rootB);
    }
    return 0;
}