Cod sursa(job #2843892)

Utilizator AdrianDiaconitaAdrian Diaconita AdrianDiaconita Data 3 februarie 2022 10:43:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NMAX = 100001;

int N, M;
int m[NMAX];
int sz[NMAX];

int Find( int x ){

    int root_x;
    int aux = x;
    while( x != m[x] ) x = m[x];

    root_x = x;
    x = aux;

    while( m[x] != root_x ){
        aux = m[x];
        m[x] = root_x;
        x = aux;
    }

    return root_x;
}

void Union( int x, int y ){
    int root_x = Find( x );
    int root_y = Find( y );

    if( root_x == root_y ) return;

    if( sz[root_x] > sz[root_y] ){
        m[root_y] = root_x;
        sz[root_x] += sz[root_y];
    }
    else{
        m[root_x] = root_y;
        sz[root_y] += sz[root_x];
    }
}

int main()
{
    fin >> N >> M;

    for( int i = 1; i <= N; ++i ){
        m[i] = i;
        sz[i] = 1;
    }

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

        if( op == 1 ) Union( x, y );
        else{
            if( Find( x ) != Find( y ) )
                fout << "NU\n";
            else fout << "DA\n";
        }
    }

    return 0;
}