Cod sursa(job #3250619)

Utilizator andreifilimonPopescu Filimon Andrei Cosmin andreifilimon Data 22 octombrie 2024 14:37:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <fstream>
#include <vector>

using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

struct DSU
{
    int N;
    vector<int> parent;

    void dsuinit(int n)
    {
        N = n;
        parent.resize(N + 1);
        int i;
        for(i = 1; i <= N; i++)
            parent[i] = 0;
    }

    int get_root(int node)
    {
        int aux = node;
        while(parent[node] > 0)
            node = parent[node];
        int root = node;
        node = aux;
        while (node != root)
        {
            aux = parent[node];
            parent[node] = root;
            node = aux;
        }
        return root;
    }

    void join(int x, int y)
    {
        int rootx = get_root(x);
        int rooty = get_root(y);
        if(rootx == rooty)
            return;
        if(parent[rootx] < parent[rooty])
        {
            parent[rootx] += parent[rooty];
            parent[rooty] = rootx;
        }
        else
        {
            parent[rooty] += parent[rootx];
            parent[rootx] = rooty;
        }
    }

    bool query(int x, int y)
    {
        return get_root(x) == get_root(y);
    }
};

int main()
{
    DSU dsu;
    int n, m;
    cin >> n >> m;
    dsu.dsuinit(n);
    int i, type, x, y;
    for(i = 0; i < m; i++)
    {
        cin >> type >> x >> y;
        if(type == 1)
        {
            dsu.join(x, y);
        }
        else
        {
            cout << (dsu.query(x, y) ? "DA\n" : "NU\n");
        }
    }
}