Cod sursa(job #2530173)

Utilizator davidbejenariu2David Bejenariu davidbejenariu2 Data 24 ianuarie 2020 14:45:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
#define N 100005
#define inf 1 << 30

using namespace std;

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

int n;
int root[N], sz[N];

int Find( int x )
{
    int rx = x, aux;

    while ( rx != root[rx] ) rx = root[rx];

    while ( x != root[x] )
    {
        aux = root[x];
        root[x] = rx;
        x = aux;
    }

    return rx;
}

void Union( int x, int y )
{
    int rx = Find( x );
    int ry = Find( y );

    if ( sz[rx] > sz[ry] )
    {
        root[ry] = rx;
        sz[rx] += sz[ry];
    }
    else
    {
        root[rx] = ry;
        sz[ry] += sz[rx];
    }
}

void read()
{
    int i, m;
    int tip, x, y;

    fin >> n >> m;

    for ( i = 1; i <= n; ++i )
    {
        root[i] = i;
        sz[i] = 1;
    }

    for ( i = 1; i <= m; ++i )
    {
        fin >> tip >> x >> y;

        if ( tip == 1 ) Union( x, y );
        else
            if ( Find( x ) == Find( y ) ) fout << "DA\n";
            else fout << "NU\n";
    }

    fin.close();
}

int main()
{
    read();

    fout.close();

    return 0;
}