Pagini recente » Cod sursa (job #1828406) | Cod sursa (job #1298933) | Cod sursa (job #704638) | Cod sursa (job #2130562) | Cod sursa (job #1374078)
#include <iostream>
#include <fstream>
#define size 100200
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int tt[size],rg[size],i,j,n,m,x,y,op;
int gaseste(int x)
{
int r,y;//r reprezinta radacine arborelui
for(r=x;tt[r]!=r;r = tt[r]);// mergem in sus pe arbore pana gasim nodul care e radacina adica tt[x]=x
while(tt[x]!=x)
{
y = tt[x]; //Urcam in arbore actualizand toti tatii lui x sa pointeze catre radacina din cap
tt[x]=r;
x = y;
}
return r;
}
void uneste(int x,int y)
{
if (rg[x]>rg[y])
tt[y] = x;
else
tt[x] = y;
if(rg[x]==rg[y])
rg[y]++; //daca rangurile erau egale cresc rangul noii multimi cu 1
}
int main()
{
in>>n>>m;
for(i=1;i<=n;i++)
{
tt[i]=i;
rg[i]=1;
}
for(i=0;i<m;i++)
{
in>>op>>x>>y;
if(op==1)
{
if(gaseste(x)!=gaseste(y))
uneste(x,y);
}
else
if (gaseste(x)==gaseste(y))
out<<"DA\n";
else
out<<"NU\n";
}
return 0;
}