Cod sursa(job #3271488)

Utilizator pkseVlad Bondoc pkse Data 26 ianuarie 2025 12:54:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

int tata[100005], h[100005];

int query(int x) {
    vector<int> w;
    while(tata[x] != x) {
        w.push_back(x);
        x = tata[x];
    }
    for(auto i:w) {
        tata[i] = x;
    }
    return x;
}

void unite(int x, int y) {
    x = query(x);
    y = query(y);
    if(h[x] == h[y])
        tata[y] = x,
        h[x] ++;
    else if(h[x] < h[y])
        tata[x] = y;
    else
        tata[y] = x;
}

int main() {
    int n, q; cin >> n >> q;
    for(int i = 1; i <= n; i ++) {
        tata[i] = i, h[i] = 1;
    }
    for(int i = 1; i <= q; i ++) {
        int c, x, y; cin >> c >> x >> y;
        if(c == 1)
            unite(x, y);
        else if(query(x) == query(y))
            cout << "DA\n";
        else
            cout << "NU\n";
    }
}