Cod sursa(job #2506964)

Utilizator niculaandreiNicula Andrei Bogdan niculaandrei Data 9 decembrie 2019 10:34:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 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)
{
    if (Size[x] > Size[y])
    {
        T[Root(y)] = Root(x);
        Size[x] += Size[y];
    }
    else
    {
        T[Root(x)] = Root(y);
        Size[y] += Size[x];
    }
}

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;
}