Cod sursa(job #2569434)

Utilizator cyg_Alex_codegicianBarbu Alexandru cyg_Alex_codegician Data 4 martie 2020 12:09:03
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda r3capitusulare Marime 0.81 kb
#include <fstream>
using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
const int nmax=100005;
int tt[nmax],rg[nmax];
void unionset(int x,int y)
{
    if (rg[x]<rg[y])
        tt[x]=y;
    else if (rg[y]<rg[x])
        tt[y]=x;
    else if (rg[x]==rg[y])
    {
        tt[y]=x;
        rg[x]++;
    }
}
int findset(int x)
{
    while (x!=tt[x])
    {
        x=tt[x];
    }
    return x;
}
int main()
{
    int n,m;
    fin >> n >> m;
    for (int i=1;i<=n;i++)
    {
        tt[i]=i;
        rg[i]=1;
    }
    while (m--)
    {
        int t,x,y;
        fin >> t >> x >> y;
        int ttx=findset(x);
        int tty=findset(y);
        if (t==1)   unionset(ttx,tty);
        else
        {
            if (ttx==tty) fout << "DA" << '\n';
            else fout << "NU" << '\n';
        }
    }
}