Cod sursa(job #2871142)

Utilizator AndreiCroitoruAndrei Croitoru AndreiCroitoru Data 12 martie 2022 21:42:43
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <bits/stdc++.h>

using namespace std;

const int N = 100001;
int sef[N];

int sefsuprem(int n)
{
    if(sef[n] == n)
        return n;
    sef[n] = sefsuprem(sef[n]);
    return sef[n];
}

void unire(int a, int b)
{
    sef[a] = sefsuprem(a);
    sef[b] = sefsuprem(b);
    sef[sef[a]] = sef[b];
}

int main()
{

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

    int n, m;
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
        sef[i] = i;
    for(int i = 1; i <= m; i++)
    {
        int t, a, b;
        cin >> t >> a >> b;
        if(t == 1)
            unire(a, b);
        else
        {
            if(sefsuprem(a) == sefsuprem(b))
                cout << "DA\n";
            else
                cout << "NU\n";
        }
    }
    return 0;
}