Cod sursa(job #1508332)

Utilizator MKLOLDragos Ristache MKLOL Data 22 octombrie 2015 15:03:48
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include<stdio.h>
#include<algorithm>
using namespace std;
int tata[101010],tip,a,b,h[101010],N,M;
int findx(int x) {
    int R = x, y;
    while(tata[R] != R)
        R = tata[R];
    while(tata[x]!=x) {
    y = tata[x];
    tata[x] = R;
    x = y;
    }
    return R;
}
void unite(int x,int y) {
    x = findx(x);
    y = findx(y);
    if (x == y) return;
    if(h[x] > h[y]) {
        tata[y]=x;
        h[x]+=h[y];
    }
    else {
        tata[x]=y;
        h[y]+=h[x];
    }
}
int main()
{
freopen("disjoint.in","r",stdin);
freopen("disjoint.out","w",stdout);
scanf("%d%d",&N,&M);
for(int i=1;i<=N;++i)
    {
    tata[i]=i;
    h[i]=1;
    }
    for(int i=1;i<=M;++i)
    {
        scanf("%d%d%d",&tip,&a,&b);
        if(tip==1)
        {
            unite(findx(a),findx(b));
        }
        if(tip==2)
        {
            if(findx(a)==findx(b))
            printf("DA\n");
            else printf("NU\n");
        }
    }


}