Cod sursa(job #1821476)

Utilizator savulescustefanSavulescu Stefan savulescustefan Data 3 decembrie 2016 11:03:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <cstdio>

using namespace std;
int n,m,i,p,x,y,x1,y1,a[100004],r[100004],x2;
int main()
{
    freopen ("disjoint.in","r",stdin);
    freopen ("disjoint.out","w",stdout);
    scanf ("%d %d", &n ,&m);
    for (i=1;i<=n;i++)
    {
        a[i]=i;
        r[i]=1;
    }
    for (i=1;i<=m;i++)
    {
        scanf ("%d %d %d", &p, &x, &y);
        if (p==1)
        {
            while (a[x]!=x)
                x=a[x];
            while (a[y]!=y)
                y=a[y];
            if (y!=x)
            {
                if (r[x]<r[y])
                    a[x]=y;
                else if (r[x]>r[y])
                    a[y]=x;
                else
                {
                    a[x]=y;
                    r[y]++;
                }
            }
        }
        else
        {
            x1=x;
            while (a[x1]!=x1)
                x1=a[x1];
            y1=y;
            while (a[y1]!=y1)
                y1=a[y1];
            if (x1==y1)
                printf ("DA\n");
            else
                printf ("NU\n");
            while (a[x]!=x)
            {
                x2=x;
                x=a[x];
                a[x2]=x1;
            }
            while (a[y]!=y)
            {
                x=y;
                y=a[y];
                a[x]=y1;
            }
        }
    }
    return 0;
}