Cod sursa(job #2776712)

Utilizator Alex_DiaconuDiaconu Alexandru Alex_Diaconu Data 20 septembrie 2021 19:30:21
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

ifstream ci ("disjoint.in");
ofstream co ("disjoint.out");

int const N=1e5+5;
vector<int> height(N), group(N);
int n, m;

int find_root(int x)
{
    int node=x;
    while (group[node]!=node)
    {
        node=group[node];
    }
    while (group[x]!=x)
    {
        int aux=group[x];
        group[x]=node;
        x=aux;
    }
    return node;
}

void unite(int x, int y)
{
    if (height[x]>height[y])
    {
        group[y]=x;
    }
    else
    {
        group[x]=y;
    }
    if (height[x]==height[y])
    {
        height[y]++;
    }
}

int main()
{
    ci >> n >> m;
    for (int i=1; i<=n; ++i)
    {
        height[i]=1;
        group[i]=i;
    }
    for (int i=1; i<=m; ++i)
    {
        int p, x, y;
        ci >> p >> x >> y;
        if (p == 1)
        {
            unite(find_root(x), find_root(y));
        }
        else
        {
            if (find_root(x)==find_root(y))
            {
                co << "DA\n";
            }
            else
            {
                co << "NU\n";
            }
        }
    }
    return 0;
}