Cod sursa(job #2862861)

Utilizator Andrei_Tud1Andrei Tudorache Andrei_Tud1 Data 5 martie 2022 22:34:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <stdio.h>
#define MAXN 100005

using namespace std;
int t[MAXN], n;

int get_root(int x)
{
    int nod = x, aux;
    while(t[x] > 0)
        x = t[x];

    while(nod != x)
    {
        aux = t[nod];
        t[nod] = x;
        nod = aux;
    }
    return x;
}

void join(int x, int y)
{
    int rootX = get_root(x), rootY = get_root(y);

    if(rootX == rootY)
        return;

    if(t[rootX] < t[rootY])
    {
        t[rootX] += t[rootY];
        t[rootY] = rootX;
    }
    else
    {
        t[rootY] += t[rootX];
        t[rootX] = rootY;
    }
}

int main()
{
    int i, m, op, x, y;
    freopen("disjoint.in", "r", stdin);
	freopen("disjoint.out", "w", stdout);

	scanf("%d %d", &n, &m);
    for(i = 1; i <= n; i++)
        t[i] = -1;
    for(i = 1; i <= m; i++)
    {
        scanf("%d %d %d", &op, &x, &y);
        if(op == 1)
        {
            join(x, y);
        }
        else
        {
            if(get_root(x) == get_root(y))
                printf("DA\n");
            else
                printf("NU\n");
        }
    }
    return 0;
}