Cod sursa(job #3137166)

Utilizator nicholas9onicaMike Krack nicholas9onica Data 11 iunie 2023 15:20:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int depth[1000001],father[1000001];
int find_rt(int node)
{
    if(node==father[node])
    {
        return node;
    }
    return father[node]=find_rt(father[node]);
}
void unire(int node1,int node2)
{
    node1=find_rt(node1);
    node2=find_rt(node2);
    if(depth[node1]<depth[node2])
    {
        father[node1]=node2;
    }
    else if(depth[node1]>depth[node2])
    {
        father[node2]=node1;
    }
    else
    {
        father[node2]=node1;
        depth[node1]++;
    }
}
int main()
{
    int n,m,cod,x,y;
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        father[i]=i;
        depth[i]=1;
    }
    for(int i=1;i<=m;i++)
    {
        fin>>cod>>x>>y;
        if(cod==1)
        {
            unire(x,y);
        }
        if(cod==2)
        {
            if(find_rt(x)==find_rt(y))
                fout<<"DA"<<"\n";
            else
                fout<<"NU"<<"\n";
        }

    }
}