Cod sursa(job #2645603)

Utilizator ZahaZaharie Stefan Zaha Data 29 august 2020 09:18:20
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
using namespace std;

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

int n, m;
int trees[100005], ranks[100005];

int find(int x) {
    int pos;

    for (pos = x; trees[pos] != pos; pos = trees[pos]);

    while (trees[x] != x) {
        int y = trees[x];
        trees[x] = pos;
        x = y;
    }

    return pos;
}

void combine(int x, int y) {
    if (ranks[x] > ranks[y])
        trees[y] = x;
    else
        trees[x] = y;

    if (ranks[x] == ranks[y])
        ++ranks[y];
}

int main() {
    fin >> n >> m;

    for (int i = 1; i <= n; ++i) {
        trees[i] = i;
        ranks[i] = i;
    }

    for (int i = 1; i <= m; ++i) {
        int type, x, y;
        fin >> type >> x >> y;

        if (type == 2)
            fout << ((find(x) == find(y)) ? "DA\n" : "NU\n");
        else
            combine(x, y);
    }

    return 0;
}