Cod sursa(job #2673920)

Utilizator Iulia14iulia slanina Iulia14 Data 18 noiembrie 2020 10:29:08
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>

using namespace std;
ifstream cin ("disjoint.in");
ofstream cout ("disjoint.out");
int set[100005];
int nr[100005];
int S(int x)
{
    if (x != set[x])
        return x = S(set[x]);
    else
        return x;
}
int unire(int x, int y)
{
    int xx = S(x);
    int yy = S(y);
    if (nr[xx] < nr[yy])
    {
        set[xx] = yy;
        nr[yy] += nr[xx];
    }
    else
    {
        set[yy] = xx;
        nr[xx] += nr[yy];
    }
}
int main()
{
    int n, i, m;
    cin >> n >> m;
    for (i = 1; i <= n; i++)
        set[i] = i, nr[i] = 1;
    for (i = 1; i <= m; i++)
    {
        int tip, x, y;
        cin >> tip >> x >> y;
        if (tip == 1)
            unire(x, y);
        else
        {
            if (S(x) == S(y))
                cout <<"DA" ;
            else
                cout << "NU";
            cout << '\n';
        }
    }
    return 0;
}