Cod sursa(job #3173470)

Utilizator Roxana_3Asavei Roxana Roxana_3 Data 22 noiembrie 2023 22:01:19
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
#define N 100000
using namespace std;

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

int n, m;
int reprez[N + 5];
int rang[N + 5];

void Initializare()
{
    for(int i = 1; i <= n; ++i)
    {
        reprez[i] = i;
        rang[i] = 1;
    }
}

int find_set(int nod)
{
    if(reprez[nod] == nod)
        return nod;
    return reprez[nod] = find_set(reprez[nod]);
}

void union_sets(int nod1, int nod2)
{
    int reprez1 = find_set(nod1);
    int reprez2 = find_set(nod2);
    if(reprez1 == reprez2)
        return;
    if(rang[reprez1] < rang[reprez2])
        swap(reprez1, reprez2);
    if(rang[reprez1] == rang[reprez2])
        rang[reprez1]++;
    reprez[reprez1] = reprez2;
}

void Rezolvare()
{
    int cod, x, y;
    for(int i = 1; i <= m; ++i)
    {
        fin >> cod >> x >> y;
        int set_x = find_set(x);
        int set_y = find_set(y);
        if(cod == 1 && set_x != set_y)
            union_sets(x, y);
        else if(cod == 2)
        {
            if(set_x == set_y)
                fout << "DA\n";
            else
                fout << "NU\n";
        }

    }
}

int main()
{
    fin >> n >> m;
    Initializare();
    Rezolvare();

    return 0;
}