Cod sursa(job #3304555)

Utilizator SimifilLavrente Simion Simifil Data 24 iulie 2025 20:37:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

const int maxn = 1e5;
int root[maxn+1], rankof[maxn+1], n, m;

int find( int varf )
{
    if( root[varf] == varf )
        return varf;
    else
    {
        int ans = find( root[varf] );
        root[varf] = ans;
        return root[varf];
    }
}

void myUnion( int a, int b )
{
    int roota = find( a );
    int rootb = find( b );

    if( rankof[roota] == rankof[rootb] )
    {
        ++rankof[roota];
        root[rootb] = roota;
    }
    else if( rankof[roota] < rankof[rootb] )
        root[roota] = rootb;
    else
        root[rootb] = roota;
}

int main() {
    ios_base::sync_with_stdio(false);
    f.tie(nullptr);
    g.tie(nullptr);

    f >> n >> m;
    for( int i = 1; i <= n; ++i )
    {
        root[i] = i;
        rankof[i] = 0;
    }
    for( int i = 1; i <= m; ++i )
    {
        int c, x, y;
        f >> c >> x >> y;
        if( c == 1 )
        {
            myUnion( x, y );
        }
        else
        {
            if( find(x) == find(y) )
                g << "DA\n";
            else
                g << "NU\n";
        }
    }

    return 0;
}