Cod sursa(job #1765713)

Utilizator GandalfTheWhiteGandalf the White GandalfTheWhite Data 26 septembrie 2016 22:17:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.7 kb
#include <cstdio>
#define N 100005
using namespace std;
int a[N],r[N],n,m;
int arb(int nod)
{
int rad=0,y;
for (rad=nod;a[rad]!=rad;rad=a[rad]);
while (a[nod]!=nod)
   {
   y=a[nod];
   a[nod]=rad;
   nod=y;
   }
return rad;
}
void reuniune(int x, int y)
{
if (r[x]>r[y]) a[y]=x;
else a[x]=y;
if (r[x]==r[y]) r[y]++;
}
int main()
{
int x,y,tip;
freopen("disjoint.in","r",stdin);
freopen("disjoint.out","w",stdout);
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++)
    {
    a[i]=i;
    r[i]=1;
    }
while (m--)
   {
   scanf("%d%d%d",&tip,&x,&y);
   if (tip==1) reuniune(arb(x),arb(y));
   else if (arb(x)==arb(y)) printf("DA\n");
        else printf("NU\n");
   }
return 0;
}