Cod sursa(job #3308425)

Utilizator tudorvoieVoie Tudor tudorvoie Data 24 august 2025 21:48:40
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, m;
int tatici[100001], rep[100001];

void init() {
    for(int i = 1; i <= n; i++) {
        tatici[i] = i;
        rep[i] = 1;
    }
}

int cauta(int x) {
    if (tatici[x] != x) {
        tatici[x] = cauta(tatici[x]);
    }
    return tatici[x];
}

void unire(int x, int y) {
    x = cauta(x);
    y = cauta(y);
    if(rep[x] < rep[y]) {
        swap(x, y);
    }
    tatici[y] = x;
    rep[x] += rep[y];
}

int main()
{
    fin >> n >> m;

    init();

    for(int i = 1; i <= m; i++) {
        int op, x, y;
        fin >> op >> x >> y;
        if(op == 1) {
            unire(x, y);
        } else {
            if(cauta(x) == cauta(y)) fout << "DA" << '\n';
            else fout << "NU" << '\n';
        }
    }
    return 0;
}