Cod sursa(job #2831769)

Utilizator vladsipunct5555Butnrau Vlad vladsipunct5555 Data 12 ianuarie 2022 09:08:50
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>
#define mod 1000000007
// https://www.youtube.com/watch?v=t5GDacP_2pQ
using namespace std;
ifstream in ("disjoint.in");
ofstream out ("disjoint.out");
int pow (int a, int b)
{
    int rez = 1;
    while (b)
    {
        if (b&1)
            rez = (rez * a) % mod;
        a = (a * a) % mod;
        b>>=1;
    }
    return rez;
}
int n, m;
int tata[100001], rang[100001];
int find_tata(int x)
{
    int cop = x;
    while (tata[x] != x)
        x = tata[x];
    while (cop != tata[cop])
    {
        int save = tata[cop];
        tata[cop] = x;
        cop = save;
    }
    return x;
}
void unite (int x, int y)
{
    int tx = find_tata(x);
    int ty = find_tata(y);
    if (rang[tx] < rang[ty])
        tata[x] = ty;
    else
        tata[y] = tx;
    if (rang[tx] == rang[ty])
        rang[ty]++;
}
void solve ()
{
    in >> n >> m;
    for (int i = 1;i<=m;++i)
    {
        int type;
        in >> type;
        if (type == 1)
        {
            int x, y;
            in >> x >> y;
            unite(x, y);
        }
        else
        {
            int x, y;
            in >> x >> y;
            if(find_tata(x) == find_tata(y))
                out << "DA\n";
            else
                out << "NU\n";
        }
    }
}
main ()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    for (int i = 1;i<=100000;++i)
        tata[i] = i;
    int t = 1;
    //cin >> t;
    while (t--)
        solve();
}