Cod sursa(job #2838298)

Utilizator MenelausSontea Vladimir Menelaus Data 23 ianuarie 2022 12:49:38
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <iostream>
#include <fstream>
#define union nulloid

std::ifstream in("disjoint.in");
std::ofstream out("disjoint.out");

const int N=100000;

int sef[N+1];

int n, m;

void union(int x, int y)
{
    int origx=x, origy=y;

    while(sef[x]!=x)
    {
        x=sef[x];
    }

    while(sef[y]!=y)
    {
        y=sef[y];
    }

    sef[y]=x;

    while(sef[origx]!=origx)
    {
        int aux=origx;
        origx=sef[origx];
        sef[aux]=x;
    }
    while(sef[origy]!=origy)
    {
        int aux=origy;
        origy=sef[origy];
        sef[aux]=x;
    }
}

bool check(int x, int y)
{
    while(sef[x]!=x)
    {
        x=sef[x];
    }
    while(sef[y]!=y)
    {
        y=sef[y];
    }

    return x==y;
}

int main()
{
    int c, x, y;

    in>>n>>m;
    for(int i=1; i<=n; i++)
    {
        sef[i]=i;
    }
    for(int i=1; i<=m; i++)
    {
        in>>c>>x>>y;
        if(c==1)
        {
            union(x, y);
        }
        else
        {
            out<<(check(x, y)? "DA\n" : "NU\n");
        }
    }
}