Cod sursa(job #1361064)

Utilizator zpaePopescu Andreea zpae Data 25 februarie 2015 19:25:31
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <cstdio>
#include <algorithm>
using namespace std;
#define NR 100002
int n,m,h[NR],r[NR];

int root(int x)
{
    int k,r;
    r=x;
    while(h[r]!=r)
        r=h[r];
    //compresie:
    while(h[x]!=x)
    {
        k=h[x];
        h[x]=r;
        x=k;
    }
    return r;
}

int unire(int x, int y)
{
    x=root(x);
    y=root(y);
    if(r[x]>r[y])
        swap(x,y);
    h[y]=x;
    if(r[x]==r[y])
        r[x]++;
}

int main()
{
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);
    int q,x,y;
    scanf("%d%d",&n,&m);
    for(q=0;q<=n;q++)
    {
        h[q]=q;
        r[q]=1;
    }
    while(m--)
    {
        scanf("%d%d%d",&q,&x,&y);
        if(q==1)
            unire(x,y);
        else
        {
            if(root(x)==root(y))
                printf("DA\n");
            else
                printf("NU\n");
        }
    }
    return 0;
}