Cod sursa(job #2886870)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 8 aprilie 2022 15:07:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

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

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

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

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

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