Cod sursa(job #1348544)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 19 februarie 2015 19:09:55
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>

using namespace std;

int getRoot(int m[], int x);
void unite(int x, int y, int r[], int m[]);

int main()
{
    int N, M, x, y, i, op;

    ifstream f("disjoint.in");
    f >> N >> M;

    int m[N + 1], r[N + 1];
    for (i = 1; i <= N; i++)
    {
        m[i] = i;
        r[i] = 1;
    }

    ofstream g("disjoint.out");
    for (i = 1; i <= M; i++)
    {
        f >> op >> x >> y;
        if (op == 1)
            unite(x, y, r, m);
        else if (op == 2)
        {
            if (getRoot(m, x) == getRoot(m, y))
                g << "DA\n";
            else
                g << "NU\n";
        }

    }
    f.close();
    return 0;
}

int getRoot(int m[], int x)
{
    int root = x;
    while (m[root] != root)
        root = m[root];

    int aux;
    while(x != m[x])
    {
        aux = m[x];
        m[x] = root;
        x = aux;
    }

    return root;
}

void unite(int x, int y, int r[], int m[])
{
    int rootX = getRoot(m, x);
    int rootY = getRoot(m, y);
    if (r[rootX] >= r[rootY])
        m[rootY] = rootX;
    else
        m[rootX] = rootY;

    if (r[rootX] == r[rootY])
        r[rootX]++;
}