Cod sursa(job #2769105)

Utilizator un_fes_galbendaniel guba un_fes_galben Data 13 august 2021 15:05:46
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
char buff[4096];
int pbuf=4095;
void readbuff()
{
    pbuf=0;
    fin.read(buff,4095);
}
int citire()
{
    int nr=0;
    if(pbuf==4095)
    {
        readbuff();
    }
    while(buff[pbuf]<'0'||buff[pbuf]>'9')
    {
        pbuf++;
        if(pbuf==4095)
        {
            readbuff();
        }
    }
    while(buff[pbuf]>='0'&&buff[pbuf]<='9')
    {
        nr=nr*10+buff[pbuf]-'0';
        pbuf++;
        if(pbuf==4095)
        {
            readbuff();
        }
    }
    return nr;
}
int sef[100005];
int h[100005];
int find1(int x){
    if(sef[x]==x){
        return x;
    }
    sef[x]=find1(sef[x]);
    return sef[x];
}
void union1(int x,int y){
    int cx=find1(x),cy=find1(y);
    int h1=h[cx],h2=h[cy];
    if(h1>=h2){
        sef[cx]=cy;
        h[cy]+=h[cx];
    }
    else{
        sef[cy]=cx;
        h[cx]+=h[cy];
    }
}
int main()
{
    int n,m,a,b,cod,c,d;
    n=citire();m=citire();
    for(int i=1;i<=n;i++){
        sef[i]=i;
        h[i]=1;
    }
    for(int i=1;i<=m;i++){
        cod=citire();a=citire();b=citire();
        if(cod==1){
            union1(a,b);
        }
        else{
           c=find1(a);d=find1(b);
           if(c==d){
                fout<<"DA"<<'\n';
           }
           else{
                fout<<"NU"<<'\n';
           }
        }
    }
    return 0;
}