Cod sursa(job #3300336)

Utilizator SimifilLavrente Simion Simifil Data 14 iunie 2025 20:26:59
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cmath>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

int parent[100003], heigt[100003];

int get_root( int node )
{
    int root = node;
    while( parent[root] != root )
        root = parent[root];
    while( node != root )
    {
        int aux = parent[node];
        parent[node] = root;
        node = aux;
    }
    return root;
}

void unite( int x, int y )
{
    int rootx = get_root(x), rooty = get_root(y);
    if( heigt[rootx] < heigt[rooty] )
    {
        parent[rootx] = rooty;
    }
    else if( heigt[rooty] < heigt[rootx] )
    {
        parent[rooty] = rootx;
    }
    else
    {
        parent[rooty] = rootx;
        heigt[rootx] += 1;
    }
}


int main()
{
    ios_base::sync_with_stdio(false);
    f.tie(nullptr);
    g.tie(nullptr);

    int n, q;
    f >> n >> q;
    for( int i = 1; i <= n; ++i )
    {
        parent[i] = i;
        heigt[i] = 1;
    }
    for( int i = 1; i <= q; ++i )
    {
        int type, x, y;
        f >> type >> x >> y;
        if( type == 1 )
        {
            unite( x, y );
        }
        else
        {
            if( get_root(x) == get_root(y) )
            {
                g << "DA\n";
            }
            else
            {
                g << "NU\n";
            }
        }
    }
    return 0;
}