Cod sursa(job #3040947)

Utilizator hhhhhhhAndrei Boaca hhhhhhh Data 30 martie 2023 17:55:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n,m;
int p[100005],sz[100005];
int dsu_get(int a)
{
    if(a!=p[a])
        return dsu_get(p[a]);
    return p[a];
}
void dsu_merge(int a,int b)
{
    a=dsu_get(a);
    b=dsu_get(b);
    if(sz[a]<sz[b])
        swap(a,b);
    p[b]=a;
    sz[a]+=sz[b];
}
int main()
{
    ios_base::sync_with_stdio(false);
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        p[i]=i;
        sz[i]=1;
    }
    while(m--)
    {
        int tip;
        fin>>tip;
        if(tip==1)
        {
            int a,b;
            fin>>a>>b;
            dsu_merge(a,b);
        }
        else
        {
            int a,b;
            fin>>a>>b;
            int x=dsu_get(a);
            int y=dsu_get(b);
            if(x==y)
                fout<<"DA\n";
            else
                fout<<"NU\n";
        }
    }
    return 0;
}