Cod sursa(job #3128701)

Utilizator SorinBossuMarian Sorin SorinBossu Data 10 mai 2023 14:47:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
constexpr int nmax = 100001;
int p[nmax], d[nmax];

int find_set(int n)
{
    if ( p[n] == n )
        return n;
    return p[n] = find_set(p[n]);
}

void union_set(int x, int y)
{
    x = find_set(x);
    y = find_set(y);
    if ( x == y )
        return;
    if ( d[x] < d[y] )
        swap(x, y);
    p[y] = x;
    d[x] = max(d[x], d[y]+1);
}
int main()
{
    int n, m;
    in >> n >> m;
    for ( int i = 1; i <= n; ++i )
       p[i] = i, d[i] = 1;
    for ( int i = 1; i <= m; ++i )
    {
        int op, x, y;
        in >> op >> x >> y;
        if ( op == 1 )
            union_set(x, y);
        else if ( find_set(x) == find_set(y) )
            out << "DA\n";
        else out << "NU\n";
    }

    return 0;
}