Cod sursa(job #2469670)

Utilizator vmnechitaNechita Vlad-Mihai vmnechita Data 7 octombrie 2019 20:29:09
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>

using namespace std;

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

void unire ( int x, int y );
void verificare ( int x, int y );

int t[100001], lg[10001];

int main()
{
    int n, m, i, c, a, b;

    fin >> n >> m;
    for ( i = 1 ; i <= n ; i++ ) lg[i] = 1;

    for ( i = 1 ; i <= m ; i++ )
    {
        fin >> c >> a >> b;
        if ( c == 1 ) unire ( a, b );
        else verificare ( a, b );
    }

    return 0;
}

void unire ( int x, int y )
{
    int cx = x, cy = y;

    while ( t[cx] != 0 ) cx = t[cx];
    while ( t[cy] != 0 ) cy = t[cy];

    if ( lg[cx] >= lg[cy] )
    {
        while ( t[x] != 0 ) x = t[x], t[x] = cx;
        while ( t[y] != 0 ) y = t[y], t[y] = cx;
        t[cy] = cx;

        if ( lg[cx] == lg[cy] ) lg[cx]++;
    }
    else
    {
        while ( t[x] != 0 ) x = t[x], t[x] = cy;
        while ( t[y] != 0 ) y = t[y], t[y] = cy;
        t[cx] = cy;
    }
}

void verificare ( int x, int y )
{
    while ( t[x] != 0 ) x = t[x];
    while ( t[y] != 0 ) y = t[y];

    if ( x == y ) fout << "DA" << '\n';
    else fout << "NU" << '\n';
}