Cod sursa(job #2716968)

Utilizator witekIani Ispas witek Data 6 martie 2021 00:21:53
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

int n, m;
vector <int> t, h;

void init() {
    t = vector <int> (n + 1);
    h = vector <int> (n + 1, 1);
    for(int i = 1; i <= n; ++i)
        t[i] = i;
}

int getRoot(int node) {
    if(node == t[node])
        return node;
    return (t[node] = getRoot(t[node]));
}

bool sameConnectedComponents(int x, int y) {
    return getRoot(x) == getRoot(y);
}

void unite(int x, int y) {
    int rootX = getRoot(x);
    int rootY = getRoot(y);
    if(sameConnectedComponents(x, y))
        return;
    if(h[rootX] < h[rootY]) {
        t[rootX] = rootY;
    }
    else {
        if(h[rootX] == h[rootY])
            ++h[rootX];
        t[rootY] = rootX;
    }
}


void solve() {
    f >> n >> m;
    init();
    int op, x, y;
    for(int i = 1; i <= m; ++i) {
        f >> op >> x >> y;
        if(op == 1) {
            unite(x, y);
        }
        else {
            if(sameConnectedComponents(x, y))
                g << "DA" << "\n";
            else g << "NU" << "\n";
        }
    }
}

int main()
{
    solve();
    return 0;
}