Cod sursa(job #3254858)

Utilizator devilexeHosu George-Bogdan devilexe Data 9 noiembrie 2024 09:13:23
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>
using namespace std;

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

const int MAXN = 1e5;
int root[MAXN + 1];
int height[MAXN + 1];
int N, M;

int getRoot(int node)
{
    if (root[node] == node)
        return node;
    return (root[node] = getRoot(root[node]));
}

void unite(int x, int y)
{
    int rootX = getRoot(x), rootY = getRoot(y);
    if (height[rootX] < height[rootY])
    {
        root[rootX] = rootY;
        ++height[rootX];
    }
    else
    {
        root[rootY] = rootX;
    }
}

int main()
{
    fin >> N >> M;
    for (int i = 1; i <= N; i++)
        root[i] = i;
    int op, a, b;
    while (M--)
    {
        fin >> op >> a >> b;
        if (op == 1)
        {
            unite(a, b);
        }
        else
        {
            fout << (getRoot(a) == getRoot(b) ? "DA" : "NU") << '\n';
        }
    }
    return 0;
}