Cod sursa(job #260034)

Utilizator marinMari n marin Data 16 februarie 2009 13:13:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.9 kb
#include <stdio.h>
#define DIM 100001
long n,m,i,x,y,cod;
long t[DIM];


long tata(long x){
  long tx;
  tx = x;
  while (t[tx]>0)
    tx = t[tx];
  return tx;
}

void join(long x, long y){
  long tx,ty;
  tx = tata(x);
  ty = tata(y);
  if (tx == ty)
    return;
  if (t[tx] < t[ty]){
    t[tx] = t[tx] + t[ty];
    t[ty] = tx;
  } else {
    t[ty] = t[tx] + t[ty];
    t[tx] = ty;
  }
}

char * query(long x,long y){
  long tx,ty;

  tx = tata(x);
  ty = tata(y);
  if (tx == ty)
     return "DA";
  else
     return "NU";
}

int main() {
  FILE *f = fopen("disjoint.in","r");
  FILE *g = fopen("disjoint.out","w");
  fscanf(f,"%ld %ld",&n, &m);
  for (i=1;i<=n;i++)
    t[i] = -1;
  for (i=1;i<=m;i++) {
    fscanf(f,"%ld %ld %ld",&cod, &x, &y);
    if (cod==1)
      join(x,y);
    else
      fprintf(g,"%s\n",query(x,y));
  }
  fclose(f);
  fclose(g);
  return 0;
}