Cod sursa(job #2816281)

Utilizator CraiuAndreiCraiu Andrei David CraiuAndrei Data 11 decembrie 2021 11:15:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
using namespace std;

/**
Paduri de multimi disjuncte
(alg. Union-Find)
4 6
1 1 2
1 3 4
2 1 3
2 1 2
1 1 3
2 1 4
*/
int t[100003], n;

/// unifica doua c.c. de radacini x si y
void Union(int x, int y)
{
    t[y] = x;
}

/// ret. radacina c.c. din care face parte nodul x
int Find(int x)
{
    int rad, y;
    rad = x;
    while (t[rad] != 0)
        rad = t[rad];
    /// comnprimam drumurile, adica toate nodurile
    /// din traseul de la x la rad se leaga direct de rad
    while (x != rad)
    {
        y = t[x];
        t[x] = rad;
        x = y;
    }
    return rad;
}

int main()
{
    int x, y, Q, op;
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    fin >> n >> Q;
    for (int k = 1; k <= Q; k++)
    {
        fin >> op >> x >> y;
        x = Find(x);
        y = Find(y);
        if (op == 1)
        {
            if (x != y) Union(x, y);
        }
        else
        {
            if (x == y) fout << "DA\n";
            else fout << "NU\n";
        }
    }
    fout.close();
    return 0;
}