Cod sursa(job #3002496)

Utilizator tomaionutIDorando tomaionut Data 14 martie 2023 20:34:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int n, m;
vector <pair<int, int> > a[100005];

struct DSU
{
    vector <int> t;

    DSU(int n)
    {
        t.resize(n + 5);
    }

    int Find(int x)
    {
        int r = x, y;
        while (t[r])
            r = t[r];

        while (x != r)
        {
            y = t[x];
            t[x] = r;
            x = y;
        }

        return r;
    }

    void Union(int x, int y)
    {
        t[x] = y;
    }
};

int main()
{
    int i, op, x, y;
    fin >> n >> m;
    DSU tree(n + 5);
    for (i = 1; i <= m; i++)
    {
        fin >> op >> x >> y;
        x = tree.Find(x);
        y = tree.Find(y);
        if (op == 1)
        {         
            if (x != y)
                tree.Union(x, y);
        }
        else
        {
            if (x == y)
                fout << "DA\n";
            else fout << "NU\n";
        }
    }


    return 0;
}