Cod sursa(job #2807600)

Utilizator mentolnothingmoreNegrut Maria Daniela mentolnothingmore Data 23 noiembrie 2021 23:06:58
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <bits/stdc++.h>

using namespace std;

int N, M, cod, x, y;

struct Forest
{
    int parent, size;
};

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

    return F;
}

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

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;
    }
}

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

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

    in >> N >> M;

    vector<Forest> f = makeForest(N);

    while (M)
    {
        M--;

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