Cod sursa(job #3350294)

Utilizator marap2011Paun Mara marap2011 Data 7 aprilie 2026 10:02:41
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <bits/stdc++.h>
#define pi pair<int,int>
using namespace std;

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

const int nmx = 1e5 + 5 ;

int t[nmx] , idk[nmx] ;

int find_root ( int node )
{
    if ( t[node] == node )
        return node ;
    else
        return t[node] = find_root ( t[node] ) ;
}

void unite ( int node_a , int node_b )
{
    int root_a = find_root ( node_a ) ;
    int root_b = find_root ( node_b ) ;

    if ( root_a != root_b )
    {
        if ( idk[root_a] < idk[root_b] )
            t[root_a] = root_b ;
        else if ( idk[root_a] > idk[root_b] )
            t[root_b] = root_a ;
        else
        {
            t[root_a] = root_b ;
            idk[root_b] ++ ;
         }
    }
}

void solve ()
{
    int n , m ;
    fin >> n >> m ;
    for ( int i = 1 ; i <= n ; i ++ )
    {
        t[i] = i ;
        idk[i] = 1 ;
    }
    for ( int i = 1 ; i <= m ; i ++ )
    {
        int c , x , y ;
        fin >> c >> x >> y ;
        if ( c == 1 )
            unite ( x , y ) ;
        else
        {
            if ( find_root ( x ) == find_root ( y ) )
                fout << "DA" << '\n' ;
            else
                fout << "NU" << '\n' ;
        }
    }
}

int main()
{
    std :: ios_base :: sync_with_stdio ( false ) ;
    fin.tie(0) ;
    fout.tie(0) ;
    solve() ;

    return 0;
}