Cod sursa(job #2822241)

Utilizator mentolnothingmoreNegrut Maria Daniela mentolnothingmore Data 23 decembrie 2021 18:48:20
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>

using namespace std;

class Forest
{
private:
    int parent, size;
public:
    static vector<Forest> makeForest(const int& N)
    {
        vector<Forest> F(N + 1);
        for (int i = 1; i <= N; ++i)
        {
            F[i].parent = i;
            F[i].size = 1;
        }

        return F;
    }

    static int findParent(int x, vector<Forest>& F)
    {
        while (F[x].parent != x)
        {
            F[x].parent = F[ F[x].parent].parent;
            F[x].size = F[F[x].parent].size;
            x = F[x].parent;
        }
        return x;
    }

    static void unionForest(int x, int y, vector<Forest>& F)
    {
        x = findParent(x, F);
        y = findParent(y, F);

        if (x == y) return;

        if (F[x].size  > F[y].size)
        {
            F[y].parent = x;
            F[x].size += F[y].size;
        }
        else
        {
            F[x].parent = y;
            F[x].size += F[x].size;
        }
    }

    static bool checkForest(int x, int y, vector<Forest>& F)
    {
        if (findParent(x, F) == findParent(y, F))
            return 1;
        return 0;
    }
};

int main()
{
    ifstream in("disjoint.in");
    int N, M;
    in >> N >> M;

    vector<Forest> f = Forest::makeForest(N);
    int x, y, cod;

    ofstream out("disjoint.out");
    while (M)
    {
        M--;

        in >> cod >> x >> y;
        if (cod == 1)   Forest::unionForest(x, y, f);
        if (cod == 2)
        {
            if (Forest::checkForest(x,y,f) == 1)
                out << "DA\n";
            else out  << "NU\n";
        }
    }
    out.close();
}