Cod sursa(job #3266421)

Utilizator iccjocIoan CHELARU iccjoc Data 8 ianuarie 2025 17:15:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int n;
vector<int> t;
vector<int> h;
void init()
{
    h.push_back(0);
    t.push_back(0);
    for(int i = 1; i <= n; i++)
    {
        h.push_back(0);
        t.push_back(i);
    }
}
int query(int x)
{
    int j = x;
    while(t[j] != j)
    {
        j = t[j];
    }
    int i = x;
    while(t[i] != i)
    {
        int aux = i;
        i = t[i];
        t[aux] = j;
    }
    return j;
}
void join(int x, int y)
{
    x = query(x);
    y = query(y);
    if(h[x] < h[y])
    {
        t[x] = y;
    }
    else if(h[x] == h[y])
    {
        t[y] = x;
        h[x]++;
    }
    else
    {
        t[y] = x;
    }
}
int main()
{
    int m;
    cin >> n >> m;
    init();
    for(int i = 0; i < m; i++)
    {
        int c, x, y;
        cin >> c >> x >> y;
        if(c == 1)
        {
            join(x, y);
        }
        else
        {
            if(query(x) == query(y))
            {
                cout << "DA\n";
            }
            else
            {
                cout << "NU\n";
            }
        }
    }
}