Cod sursa(job #2371126)

Utilizator alexandra_paticaAndreea Alexandra Patica alexandra_patica Data 6 martie 2019 16:04:16
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>
#include <algorithm>
using namespace std;
ifstream f ("disjoint.in");
ofstream g ("disjoint.out");

int n, m, arr[100001], len[100001], tip, x, y;

int root (int x)
{
    while (arr[x]!=x)
    {
        arr[x]=arr[arr[x]];
        x=arr[x];
    }
    return x;
}

bool Find (int x, int y)
{
    if (root(x)==root(y)) return true;
    return false;
}

void Union (int a, int b)
{
    int root_a = root(a);
    int root_b = root(b);

    if (len[root_a]>len[root_b])
    {
        arr[root_b]=root_a;
        len[root_a]+=len[root_b];
    }
    else
    {
        arr[root_a]=root_b;
        len[root_b]+=len[root_a];
    }
}

int main ()
{
    f >> n >> m;
    for (int i=1; i<=n; i++)
    {
        arr[i]=i;
        len[i]=1;
    }
    for (int i=1; i<=m; i++)
    {
        f >> tip >> x >> y;
        if (tip==1)
        {
            if (!Find(x, y)) Union(x, y);
        }
        else
        {
            if (Find(x, y)) g << "DA\n";
            else g << "NU\n";
        }
    }
    return 0;
}