Cod sursa(job #2870895)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 12 martie 2022 17:25:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>

using namespace std;

const string filename = "disjoint";
ifstream fin(filename + ".in");
ofstream fout(filename + ".out");

const int maxN = 100005;
int n, q, root[maxN], depth[maxN];

int findroot(int x)
{
    if(root[x] == 0)
        return x;
    return findroot(root[x]);
}

void join(int x, int y)
{
    if(depth[x] == depth[y])
        root[x] = y, depth[y]++;
    if(depth[x] < depth[y])
        root[x] = y;
    if(depth[x] > depth[y])
        root[y] = x;
}

int main()
{
    fin >> n >> q;
    for(int i = 1; i <= q; i++)
    {
        int cer, x, y;
        fin >> cer >> x >> y;
        x = findroot(x);
        y = findroot(y);
        if(cer == 1)
            join(x, y);
        if(cer == 2)
        {
            if(x == y)
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}