Cod sursa(job #3370483)

Utilizator teobsnTeodor Bostan teobsn Data 26 octombrie 2026 14:23:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <iostream>
#include <fstream>
using namespace std;

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

const int NMAX = 1e5;
int p[NMAX + 1], sz[NMAX + 1];

int Find(int x)
{
    /*
        Return root of the tree x is part of
    */
    while (x != p[x])
        x = p[x];

    return x;
}

void Union(int x, int y)
{
    /*
        Make a union of the two trees (x and y are part of)
    */
    x = Find(x);
    y = Find(y);
    if (sz[x] > sz[y])
    {
        p[y] = x;
        sz[x] += sz[y];
    }
    else
    {
        p[x] = y;
        sz[y] += sz[x];
    }
}

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 {
            fout << (Find(x) == Find(y) ? "DA\n" : "NU\n");
        }
    }

    return 0;
}