Cod sursa(job #2058802)

Utilizator GeorgeCalinPetruta George-Calin GeorgeCalin Data 6 noiembrie 2017 10:17:52
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>
#define nmax 100002
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

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

int cauta(int x)
{
    int r,y;
    r=x;
    while(t[r]!=r)
        r=t[r];
    while(t[x]!=x)
    {
        y=t[x];
        t[x]=r;
        x=y;
    }
    return r;
}

void unire(int x,int y)
{
    if(rg[y]>rg[x])
        t[y]=t[x];
    else
        t[x]=t[y];
    if(rg[x]==rg[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>>c>>x>>y;
        if(c==2)
        {
            if(cauta(x)==cauta(y))
            {
                fout<<"DA\n";
            }
            else
                fout<<"NU\n";
        }
        else
        {
            unire(cauta(x),cauta(y));
        }
    }
    return 0;
}