Cod sursa(job #2457017)

Utilizator dimi999Dimitriu Andrei dimi999 Data 16 septembrie 2019 11:41:51
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.88 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int rnk[100005],dad[100005];
int n,m,cod,x,y;


int root(int nod)
{
    int nodinit=nod, x=dad[nod];
    while(nod!=x)
    {
        nod=x;
        x=dad[nod];
    }
    dad[nodinit]=x;
    return x;
}


void join(int x,int y)
{
    x=root(x);
    y=root(y);
    if(rnk[x]>rnk[y])
        dad[y]=x;
    else
        if(rnk[y]>rnk[x])
        dad[x]=y;
    else
        rnk[y]++,dad[x]=y;
}


int main()
{
    int i;
    fin>>n>>m;
    for(i=1;i<=n;i++)
        dad[i]=i;
    for(i=1;i<=m;i++)
    {
        fin>>cod>>x>>y;
        if(cod==1)
            join(x,y);
        else
        {
            if(root(x)==root(y))
                fout<<"DA"<<'\n';
            else
                fout<<"NU"<<'\n';
        }
    }
    return 0;
}