Cod sursa(job #228425)

Utilizator mihai_floreaFlorea Mihai Alexandru mihai_florea Data 7 decembrie 2008 11:00:20
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 0.81 kb
#include <stdio.h>
#define NMAX 100001
int N,M,t[NMAX],nr[NMAX];
int find(int x){
    int rad=x,y=x,z;
    while (t[rad]!=rad) rad=t[rad];
    //compresie
    while (y!=rad){
      z=t[y];
      t[y]=rad;
      y=z;}
    return rad;
    }
void unite(int x,int y){
     if (x==y) return;
     if (nr[x]<nr[y])
      {
       t[x]=y;
       nr[y]+=nr[x];
      }
      else
      {
       t[y]=x;
       nr[x]+=nr[y];
      }
     }
int main(){
    int i,j,k;
    freopen("disjoint.in","r",stdin);
    freopen("disjoint.out","w",stdout);
    scanf("%d %d",&N,&M);
    for (i=1;i<=N;++i) t[i]=i,nr[i]=1;
    while(M--){
      scanf("%d %d %d",&k,&i,&j);
      if (k==1) unite(find(i),find(j));
       else printf("%s\n",find(i)==find(j)?"DA":"NU");
      }
    return 0;
}