Cod sursa(job #2791039)

Utilizator witekIani Ispas witek Data 29 octombrie 2021 23:52:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

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

void init() {
    h = vector <int> (n + 1);
    t = vector <int> (n + 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(rootX == rootY)
        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 g << (sameConnectedComponents(x, y) ? "DA\n" : "NU\n");
    }
}

int main()
{
    solve();
}