Cod sursa(job #3120905)

Utilizator alexei_barosuAlexei Niculae alexei_barosu Data 9 aprilie 2023 12:10:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int N,M;
vector < int > mult;
vector < int > sz;

int Find (int val)
{
    int root=val;
    while (mult[root]!=root)
        root=mult[root];
    int aux;
    while (mult[val]!=root)
    {
        aux=mult[val];
        mult[val]=root;
        val=aux;
    }
    return root;
}

void Union(int a,int b)
{
    int root_a=Find(a);
    int root_b=Find(b);
    if (sz[root_a]<sz[root_b])
    {
        sz[root_a]+=sz[root_b];
        mult[root_b]=root_a;
    }
    else
    {
        sz[root_b]+=sz[root_a];
        mult[root_a]=root_b;
    }
}

int main()
{
    fin>>N>>M;
    mult.resize(N+1);
    sz.resize(N+1);
    for (int i=1; i<=N; i++)
    {
        mult[i]=i;
        sz[i]=1;
    }
    for (int i=1; i<=M; i++)
    {
        int cod,x,y;
        fin>>cod>>x>>y;
        if (cod==1)
        {
            Union(x,y);
        }
        else
        {
            if (Find(x)==Find(y))
                fout<<"DA"<<endl;
            else
                fout<<"NU"<<endl;
        }
    }
    return 0;
}