Cod sursa(job #3371392)

Utilizator Teooo28Aghirasimoae Andra Teodora Teooo28 Data 30 octombrie 2026 08:30:24
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>
using namespace std;

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

int p[100001], sz[1000001];

int Find(int x) {
    while(x != p[x]) {
        x = p[x];
    }
    return x;
}

void Union(int x, int y) {
    x = Find(x);
    y = Find(y);
    if(sz[x] < sz[y]) {
        p[x] = y;
        sz[y] += sz[x];
    } else {
        p[y] = x;
        sz[x] += sz[y];
    }
}

int main() {
    int n, q;
    fin >> n >> q;
    for(int i = 1; i <= n; i++) {
        p[i] = i;
        sz[i] = 1;
    }
    for(int i = 1; i <= q; i++) {
        int op, x, y;
        fin >> op >> x >> y;
        if(op == 1) {
            Union(x, y);
        } else if (op == 2) {
            if (Find(x) == Find(y)) {
                fout << "DA\n";
            } else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}