Cod sursa(job #2408865)

Utilizator gabrielmGabriel Majeri gabrielm Data 18 aprilie 2019 13:32:09
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <algorithm>
#include <fstream>
#include <iostream>
#include <numeric>
#include <vector>

using namespace std;

vector<int> tati, grad;

void print() {
    for (int tata : tati) {
        cout << tata << ' ';
    }
    cout << '\n';
    for (int gr : grad) {
        cout << gr << ' ';
    }
    cout << '\n';
}

int find_father(int nod) {
    if (tati[nod] == nod) {
        return nod;
    } else {
        return tati[nod] = find_father(tati[nod]);
    }
}

int main() {
    ifstream in("disjoint.in");
    int n;
    in >> n;

    tati.resize(n);
    iota(tati.begin(), tati.end(), 0);

    grad.resize(n, 1);

    ofstream out("disjoint.out");

    int m;
    in >> m;
    for (int i = 0; i < m; ++i) {
        int operatie, x, y;
        in >> operatie >> x >> y;

        --x;
        --y;

        int tata_x = find_father(x);
        int tata_y = find_father(y);

        if (operatie == 1) {
            if (tata_x != tata_y) {
                if (grad[tata_x] < grad[tata_y]) {
                    tati[tata_x] = tata_y;
                    grad[tata_y] += grad[tata_x];
                } else {
                    tati[tata_y] = tata_x;
                    grad[tata_x] += grad[tata_y];
                }
            }
        } else {
            if (tata_x == tata_y) {
                out << "DA";
            } else {
                out << "NU";
            }
            out << '\n';
        }
    }
}