Cod sursa(job #2946847)

Utilizator crivoicarlaCrivoi Carla crivoicarla Data 25 noiembrie 2022 10:39:39
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
//
// Created by Carla on 11/24/2022.
//
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

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

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]));
}

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

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

}

int main() {
    int x, y, op;
    fin >> n >> m;
    init();
    for(int i = 1; i <= m; i ++) {
        fin >> op >> x >> y;
        if(op == 1) unite(x, y);
        else fout << (sameConnectedComponents(x, y) ? "DA\n" : "NU\n");
    }
    return 0;
}