Cod sursa(job #3129400)

Utilizator hurjui12AlexandruHurjui Alexandru-Mihai hurjui12Alexandru Data 14 mai 2023 12:53:18
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
using namespace std;
using llx = long long;

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

vector<int> t, h;

void init(int n)
{
    t.assign(n+1, 0);
    h.assign(n+1, 0);
}

void uneste(int x, int y)
{
    if (h[x] < h[y])
        t[x] = y;
    else
    {
        t[y] = x;
        if (h[x] == h[y])
            h[x]++;
    }
}

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

int main()
{
    int n, m, i, op, x, y;

    fin >> n >> m;
    init(n);

    for (i = 1; i<=m; i++)
    {
        fin >> op >> x >> y;

        if (op == 1)
            uneste(find(x), find(y));
        else
        {
            if (find(x) == find(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}