Cod sursa(job #2478490)

Utilizator XsoundCristian-Ioan Roman Xsound Data 22 octombrie 2019 10:43:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>
#define Nmax 100005
using namespace std;

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

int rang [Nmax], t[Nmax];
int n, m, x, y, op;

void citire();

void leg ( int a, int b )
{
    while ( t[b] != b)
    {
        b = t[b] ;
        t[b] = a;
    }
}


int cauta( int a )
{
    while ( t[a]!= a )
        a = t[a];

    return a;
}

bool is()
{
    int k1 = cauta(x);
    int k2 = cauta(y);

    leg(k1,x);
    leg(k2,y);

    return (k1==k2);
}

void reunesc()
{
    int k1 = cauta(x), k2 = cauta(y);

    leg(k1, x);

    leg(k2, y);

    x = k1;
    y = k2;

    if ( rang[x] == rang [y] )
    {
        if ( x < y )
        {
            rang [x]++;
            t[y] = x;
        }

        else
        {
            rang [y]++;
            t[x] = y;
        }
    }

    else if ( rang [x] > rang [y] )
        t[y] = x;

    else t[x] = y;

}

int main()
{
    citire();
    return 0;
}

void citire()
{
    fin >> n >> m;

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

        if ( t[x] == 0)
            t[x] = x;

        if ( t[y] == 0)
            t[y] = y;

        if ( op == 1 )
            reunesc();
        else
           if ( is() ) fout << "DA\n";
           else fout << "NU\n";
    }
}