Cod sursa(job #2684667)

Utilizator SochuDarabaneanu Liviu Eugen Sochu Data 14 decembrie 2020 14:51:56
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
#define FastIO ios_base::sync_with_stdio(false) , cin.tie(0) , cout.tie(0)
#define FILES freopen("disjoint.in" , "r" , stdin) , freopen("disjoint.out" , "w" , stdout)

using namespace std;

const int N = 1e5 + 10;

int n , m , x , y , type;
int roots[N] , heights[N];

int F(int x)
{
    int R = x;

    for( ; R != roots[R] ; R = roots[R]);

    for( ; roots[x] != x ; )
    {
        int next = roots[x];
        roots[x] = R;
        x = next;
    }
}

void unite(int x , int y)
{
    int rx = F(x);
    int ry = F(y);

    if(rx == ry)
        return;

    if(heights[rx] < heights[ry])
        roots[rx] = ry;
    else if(heights[rx] > heights[ry])
        roots[ry] = rx;
    else
    {
        roots[rx] = ry;
        ++heights[ry];
    }
}

signed main()
{
	#ifndef ONLINE_JUDGE
		FastIO , FILES;
	#endif

    cin >> n >> m;

    for(int i = 1 ; i <= n ; i++)
    {
        roots[i] = i;
        heights[i] = 1;
    }

    for(int i = 1 ; i <= m ; i++)
    {
        cin >> type >> x >> y;

       if(type == 1)
            unite(x , y);
       else if(F(x) == F(y))
            cout << "DA\n";
       else cout << "NU\n";
    }

    return 0;
}