Cod sursa(job #2968288)

Utilizator cristiWTCristi Tanase cristiWT Data 20 ianuarie 2023 21:32:14
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>

#define ll long long

using namespace std;

const int NMAX = 1e5 + 10;
int n, m, p[NMAX];

int find(int x) {
    int ans = x, aux = x;
    while (p[ans] != ans)
        ans = p[ans];
    while (aux != ans) {
        int cpy = aux;
        aux = p[aux];
        p[cpy] = ans;
    }
    return ans;
}

void unite(int x, int y) {
    p[find(x)] = find(y);
}

signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr), cout.tie(nullptr);
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    cin >> n >> m;
    for (int i = 1; i <= n; i++)
        p[i] = i;
    while (m--) {
        int op, x, y;
        cin >> op >> x >> y;
        if (op == 1) unite(x, y);
        else cout << (find(x) == find(y) ? "DA\n" : "NU\n");
    }
}