Cod sursa(job #3203445)

Utilizator tudor_bustanBustan Tudor Gabriel tudor_bustan Data 13 februarie 2024 17:56:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <iostream>
#include <fstream>
#include <bits/stdc++.h>
#define inf INT_MAX
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n, q, task, x, y, t[100001], height[100001];
int fnd(int x)
{
    if(t[x]!=x)
    {
        return fnd(t[x]);
    }
    return t[x];
}
void uneste(int a, int b)
{
    a=fnd(a), b=fnd(b);
    if(height[a]<height[b])
    {
        t[a]=b;
    }
    else t[b]=a;
    if(height[a]==height[b])
    {
        height[b]++;
    }
}
int main()
{
    fin>>n>>q;
    for(int i=1; i<=n; i++)
    {
        t[i]=i;
        height[i]=1;
    }
    while(q)
    {
        fin>>task>>x>>y;
        if(task==1)
        {
            uneste(x, y);
        }
        else
        {
            if(fnd(x)==fnd(y))
            {
                fout<<"DA"<<"\n";
            }
            else fout<<"NU"<<"\n";
        }
        q--;
    }
    return 0;
}