Cod sursa(job #2940304)

Utilizator eva_simpetruEva Maria Simpetru eva_simpetru Data 15 noiembrie 2022 11:28:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int n, m,tip, x, y, grad[100000], tata[100000];


int gasesc(int x) {
    int xinit = x;
    while (tata[x] != x)
        x = tata[x];
    while (xinit != x) {
        tata[xinit] = x;
        xinit = tata[xinit];
    }
    return x;
}

void unesc(int x, int y) {
    int tatx = gasesc(x), taty = gasesc(y);
    if (grad[tatx] > grad[taty])
        tata[taty] = tatx;
    else
        tata[tatx] = taty;
    if (grad[tatx] == grad[taty])
        ++grad[taty];
}

void afisRez(int x, int y) {
    if (gasesc(x) == gasesc(y))
        fout << "DA\n";
    else
        fout << "NU\n";
}


int main() {

    fin >> n >> m;
    for (int i = 0; i < n; ++i) {
        grad[i] = 1;
        tata[i] = i;
    }
    for (int i = 0; i < m; ++i) {
        fin >> tip >> x >> y;
        if (tip == 1) {
            unesc(x, y);
        } else {
            afisRez(x, y);
        }
    }
}