Cod sursa(job #2067418)

Utilizator GeorgeCalinPetruta George-Calin GeorgeCalin Data 16 noiembrie 2017 13:15:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>
#define nmax 100002
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int t[nmax];
int rg[nmax];

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

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


int main()
{
    int n,m,c,x,y;
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        t[i]=i;
        rg[i]=1;
    }
    for(int i=1;i<=m;i++)
    {
        fin>>c>>x>>y;
        if(c==1)
        {
            unire(gaseste(x),gaseste(y));
        }
        else
        {
            if(gaseste(x)==gaseste(y))
                fout<<"DA\n";
            else
                fout<<"NU\n";
        }
    }
    return 0;
}