Cod sursa(job #2296024)

Utilizator cahemanCasian Patrascanu caheman Data 4 decembrie 2018 09:49:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include<cstdio>

using namespace std;

int dad[100005], height[100005];

int find_root(int node)
{
    int c, root, prevc;
    c = node;
    while(dad[c] != 0)
    {
        c = dad[c];
    }
    root = c;
    c = node;
    while(dad[c] != 0)
    {
        prevc = c;
        c = dad[c];
        dad[prevc] = root;
    }
    return root;
}

void mica_unire(int node1, int node2)
{
    int groot1, groot2;
    groot1 = find_root(node1);
    groot2 = find_root(node2);
    if(height[groot1] == height[groot2])
    {
        ++ height[groot1];
        dad[groot2] = groot1;
    }
    else
    {
        if(height[groot1] > height[groot2])
            dad[groot2] = groot1;
        else
            dad[groot1] = groot2;
    }
}

int main()
{
    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);
    int x, y, i, n, m, tip;
    scanf("%d%d", &n, &m);
    for(i = 1; i <= m; ++ i)
    {
        scanf("%d%d%d", &tip, &x, &y);
        if(tip == 1)
            mica_unire(x, y);
        else
        {
            if(find_root(x) != find_root(y))
                printf("NU\n");
            else
                printf("DA\n");
        }
    }
    return 0;
}