Cod sursa(job #2506966)

Utilizator niculaandreiNicula Andrei Bogdan niculaandrei Data 9 decembrie 2019 10:39:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
#define N_MAX 100005

using namespace std;

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

int n, m, op, x, y;
int T[N_MAX], Size[N_MAX];

int Root(int x)
{
    int root = x, y = x;
    while (x != T[x])
    {
        x = T[x];
        root = x;
    }
    while (y != T[y])
    {
        x = y;
        y = T[y];
        T[x] = root;
    }
    return root;
}

void Union(int x, int y)
{
    int root_x = Root(x), root_y = Root(y);
    if (Size[root_x] > Size[root_y])
        T[Root(root_y)] = Root(root_x);
    else
        T[root_x] = Root(root_y);
    if (Size[root_x] == Size[root_y])
        Size[root_y]++;
}

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= n; i++)
    {
        Size[i] = 1;
        T[i] = i;
    }
    while (m--)
    {
        fin >> op >> x >> y;
        if (op == 1)
            Union(x, y);
        else if (op == 2)
        {
            if (Root(x) == Root(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}