Cod sursa(job #2469641)

Utilizator N0NameLupulescu Vasile N0Name Data 7 octombrie 2019 20:03:41
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 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 )
{
    while ( t[x] != 0 ) x = t[x];
    while ( t[y] != 0 ) y = t[y];

    if ( lg[y] < lg[x] ) t[y] = x, lg[y] = 0;
    else if ( lg[x] == lg[y] ) t[y] = x, lg[y] = 0, lg[x]++;
    else t[x] = y, lg[x] = 0;
}

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';
}