Cod sursa(job #2698146)

Utilizator patriciaxdBraica Patricia patriciaxd Data 21 ianuarie 2021 09:27:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int N,M;
int P[100001];
int V[100001];

int f(int x)
{
    if (x==P[x])
        return x;
    else
        return f(P[x]);
}

void uniune(int a, int b)
{
    int pa,pb;
    pa=f(a);
    pb=f(b);
    if (pa!=pb)
        if (V[pa]<=V[pb])
        {
            V[pb]+=V[pa];
            P[pa]=pb;
        }
        else
        {
            V[pa]+=V[pb];
            P[pb]=pa;
        }
}

int main()
{
    in>>N>>M;
    for (int i=1; i<=N; i++)
    {
        P[i]=i;
        V[i]=1;
    }
    int cod,x,y;
    for(int i=1; i<=M; i++)
    {
        in>>cod>>x>>y;
        if(cod==1)
            uniune(x,y);
        else
        {
            int px=f(x);
            int py=f(y);
            if(py==px)
                out<<"DA";
            else
                out<<"NU";
            out<<'\n';
        }
    }
    in.close();
    out.close();
    return 0;
}