Cod sursa(job #1291782)

Utilizator harababurelPuscas Sergiu harababurel Data 13 decembrie 2014 11:38:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.76 kb
#include <iostream>
#include <fstream>
#include <cmath>
#define nmax 100005
using namespace std;

int n, m, op, x, y, A, B, p[nmax];

void join(int root1, int root2) {
  if(abs(p[root1]) > abs(p[root2])) {
    p[root1] += p[root2];
    p[root2] = root1;
  }
  else {
    p[root2] += p[root1];
    p[root1] = root2;
  }
}

int find(int x) {
  if(p[x] < 0) return x;
  p[x] = find(p[x]);

  return p[x];
}  



int main() {
  ifstream f("disjoint.in");
  ofstream g("disjoint.out");

  f>>n>>m;
  for(int i=1; i<=n; i++) p[i] = -1;
  for(int i=1; i<=m; i++) {
    f>>op>>x>>y;
    int A=find(x), B=find(y);

    if(op == 1) join(A, B);
    else {
      if(A == B) g<<"DA\n";
      else g<<"NU\n";
    }
  }

  return 0;
}