Cod sursa(job #2408853)

Utilizator gabrielmGabriel Majeri gabrielm Data 18 aprilie 2019 13:25:35
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 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 {
        int tata = find_father(tati[nod]);
        tati[nod] = tata;
        return tata;
    }
}

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_y] > grad[tata_x]) {
                    tati[y] = x;
                    grad[tata_x] += grad[tata_y];
                } else {
                    tati[x] = y;
                    grad[tata_y] += grad[tata_x];
                }
            }
        } else {
            out << (tata_x == tata_y ? "DA" : "NU") << '\n';
        }

        print();
    }
}