Cod sursa(job #2845115)

Utilizator teodorescunicolasteodorescu nicolas alexandru teodorescunicolas Data 7 februarie 2022 15:21:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <stdio.h>

#define NMAXX 100000

using namespace std;

int v[NMAXX + 1], h[NMAXX + 1];

int find( int x ) {
    if ( v[x] == x )
        return x;
    return v[x] = find( v[x] );
}

void unite( int x, int y ) {
    int setx, sety;

    setx = find( x );
    sety = find( y );

    if ( setx != sety ) {
        if ( h[setx] < h[sety] )
            v[setx] = sety;
        else if ( h[setx] > h[sety] )
            v[sety] = setx;
        else {
            v[setx] = sety;
            h[sety]++;
        }
    }
}

int main()
{
    FILE *fin, *fout;
    int n, m, i, cer, x, y;

    fin = fopen( "disjoint.in", "r" );
    fout = fopen( "disjoint.out", "w" );

    fscanf( fin, "%d%d", &n, &m );

    for ( i = 1; i <= n; i++ ) {
        v[i] = i;
        h[i] = 1;
    }

    for ( i = 0; i < m; i++ ) {
        fscanf( fin, "%d%d%d", &cer, &x, &y );
        if ( cer == 1 )
            unite( x, y );
        else {
            if ( find( x ) == find( y ) )
                fprintf( fout, "DA\n" );
            else
                fprintf( fout, "NU\n" );
        }
    }

    fclose( fin );
    fclose( fout );
    return 0;
}