Cod sursa(job #2920740)

Utilizator LucaMuresanMuresan Luca Valentin LucaMuresan Data 25 august 2022 16:20:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>

using namespace std;

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

const int dim = 1e5+1;

int t[dim], cnt[dim];

int root (int x)
{
    if (t[x] == x)
        return x;
    t[x] = root(t[x]);
    return t[x];
}

void unite (int x, int y)
{
    x = root(x);
    y = root(y);

    if (x != y)
    {
        if (cnt[x] < cnt[y])
            swap(x, y);
    }

    t[y] = x;
    cnt[x] += cnt[y];
}

int main()
{

    int n, q;
    in >> n >> q;

    for (int i=1; i<=n; i++)
        t[i] = i, cnt[i] = 1;

    while (q--)
    {
        int op, x, y;
        in >> op >> x >> y;

        if (op == 1)
            unite(x, y);
        else
        {
            if (root(x) == root(y))
                out << "DA";
            else
                out << "NU";
            out << '\n';
        }
    }

    return 0;
}