Cod sursa(job #2977028)

Utilizator Kawaiimeatball13Russu Mihaela Kawaiimeatball13 Data 10 februarie 2023 17:47:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

int t[100001];
int h[100001];

int n, k;

void initializare()
{
    for(int i = 1; i <= n; ++i)
    {
        t[i] = i;
        h[i] = 1;
    }

}

int gasim_tata(int x)
{
    int aux = x;
    while(t[x] != x)
        x = t[x];
    while(aux != x)
    {
        int next = t[aux];
        t[aux] = x;
        aux = next;
    }
    return x;
}

void unire(int x, int y)
{
    int tata_y = gasim_tata(y);
    int tata_x = gasim_tata(x);
    if(h[tata_y] < h[tata_x])
    {
        t[tata_y] = tata_x;
        h[tata_y] = h[tata_x];
    }
    else if(h[tata_x] < h[tata_y])
    {
        t[tata_x] = tata_y;
        h[tata_x] = h[tata_y];
    }
    else
    {
        t[tata_x] = tata_y;
        h[tata_y]++;
        h[tata_x] = h[tata_y];
    }
}

void rezolvare()
{
    int op, x, y;
    for(int j = 0; j < k; ++j)
    {
        fin >> op >> x >> y;
        if(op == 1)
            unire(x, y);
        else
        {
            if(gasim_tata(x) == gasim_tata(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
}

int main()
{
    fin >> n >> k;
    initializare();
    rezolvare();
    return 0;
}