Cod sursa(job #2361760)

Utilizator FrequeAlex Iordachescu Freque Data 2 martie 2019 18:26:07
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int NMAX = 100000 + 5;

int n, m;
int root[NMAX], rang[NMAX];

void read()
{
    fin >> n >> m;
    for (int i = 1; i <= n; ++i)
    {
        root[i] = i;
        rang[i] = 1;
    }
}

int find_root(int x)
{
    int i;
    for (i = x; i != root[i]; i = root[i]);

    while (x != root[x])
    {
        int y = root[x];
        root[x] = i;
        x = y;
    }

    return i;
}

void unite(int x, int y)
{
    if (rang[x] > rang[y])
    {
        rang[x] += rang[y];
        root[y] = x;
    }
    else
    {
        rang[y] += rang[x];
        root[x] = y;
    }
}

int main()
{
    int cod, x, y;
    read();

    for (int i = 1; i <= m; ++i)
    {
        fin >> cod >> x >> y;
        if (cod == 1)
        {
            if (find_root(x) != find_root(y))
                unite(find_root(x), find_root(y));
        }
        else
        {
            if (find_root(x) == find_root(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }

    return 0;
}