Cod sursa(job #2808257)

Utilizator Angel2IonitaAngel Ionita Angel2Ionita Data 24 noiembrie 2021 19:38:00
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream f("disjoint.in");
ofstream o("disjoint.out");

class DisjointSets
{
    vector<int> rank, parent;
    int size;
public:
    DisjointSets(int n)
    {
        size = n+1;
        rank.resize(size);
        parent.resize(size);
        for (int i = 1; i < size; i++)
        {
            parent[i] = i;
            rank[i] = 1;
        }
    }
    int Find(int x)
    {
        if(parent[x]==x)
            return x;
        return Find(parent[x]);
    }

    void Union(int x, int y)
    {
        int fx = Find(x);
        int fy = Find(y);
        if (rank[fx] < rank[fy])
            parent[fx] = fy;
        else
            parent[fy] = fx;
        if(rank[fx]==rank[fy])
            rank[fx]++;
    }
};

int main()
{
    int N, M;
    int cod, x, y;
    f >> N >> M;
    DisjointSets ds(N);
    for (int i = 1; i <= M; i++)
    {
        f >> cod >> x >> y;
        if (cod == 1)
            ds.Union(x, y);
        else if (ds.Find(x) == ds.Find(y))
            o << "DA";
        else
            o << "NU";
        o<<endl;
    }
    return 0;
}