Cod sursa(job #1417408)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 10 aprilie 2015 11:56:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include <bits/stdc++.h>

using namespace std;

class UnionFind
{
public:

    explicit UnionFind(){
    }

    UnionFind(const int n) : Parent(vector<int>(n + 1, 0)), Rank(vector<int>(n + 1, 0)) {

        for (int i = 1; i <= n; ++i)
            MakeSet(i);
    }

    void MakeSet(int x)
    {
        Parent[x] = x;
        Rank[x] = 0;
    }

    int Find(int x)
    {
        if (Parent[x] != x)
            Parent[x] = Find(Parent[x]);

        return Parent[x];
    }

    void Union(int x, int y)
    {
        x = Find(x);
        y = Find(y);

        if (x != y)
        {
            if (Rank[x] > Rank[y])
                Parent[y] = x;
            else
                Parent[x] = y;

            if (Rank[x] == Rank[y])
                Rank[y]++;
        }
    }

    bool connected(int x, int y)
    {
        return Find(x) == Find(y);
    }

private:

    vector<int> Parent;
    vector<int> Rank;
};

int main()
{
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    int N, Q;
    in >> N >> Q;

    UnionFind D(N);

    while (Q--)
    {
        int tip, x, y;

        in >> tip >> x >> y;

        if (tip == 1)
            D.Union(x, y);
        else
        {
            if (D.connected(x, y))
                out << "DA\n";
            else
                out << "NU\n";
        }
    }

    return 0;
}