Cod sursa(job #2126101)

Utilizator antanaAntonia Boca antana Data 9 februarie 2018 10:21:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fi ("disjoint.in" );
ofstream fo ("disjoint.out");

const int maxn = 1e5 + 5;

int n, m, dad[maxn];

int father( int x ) {
    if (x == dad[ x ])
        return x;
    return dad[ x ] = father( dad[ x ] ); // compactez drumurile si aflu tatal
}

void join( int x, int y ) {
    int fx = father( x ), fy = father( y ); // unesc multimi, las compactarea pentru alta data
    dad[ fx ] = fy;
}

int main()
{
    fi >> n >> m;

    for (int i = 1; i <= n; i++)
        dad[ i ] = i; // initial, fiecare element e tatal sau

    int x, y, type;
    while (m--) {
        fi >> type >> x >> y;
        if (type == 1)
            join( x, y );
        else {
            int rx = father( x ), ry = father( y );
            if (rx == ry)
                fo << "DA" << '\n';
            else
                fo << "NU" << '\n';
        }
    }

    fo.close();
    fi.close();

    return 0;
}