Cod sursa(job #2424148)

Utilizator PopescuAndreiAlexandruPopescu Andrei Alexandru PopescuAndreiAlexandru Data 22 mai 2019 18:08:16
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;

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

#define nmax 100005

int rg[nmax],t[nmax],n,m,x,y,task;

int Find(int nod)
{
    while(t[nod]!=nod)
        nod=t[nod];
    return nod;
}

void Union(int x, int y)
{
    if(rg[x]<rg[y])
        t[x]=t[y];
    if(rg[x]>rg[y])
        t[y]=t[x];
    if(rg[x]==rg[y])
    {
        t[x]=t[y];
        rg[y]++;
    }
}

int main()
{
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        rg[i]=1;
        t[i]=i;
    }
    for(int i=1;i<=m;i++)
    {
        fin>>task>>x>>y;
        switch(task)
        {
        case 1:
            {
                Union(x,y);
                break;
            }
        case 2:
            {
                if(Find(x)!=Find(y))
                    fout<<"NU"<<'\n';
                else
                    fout<<"DA"<<'\n';
                break;
            }
        }
    }
}