Cod sursa(job #2073906)

Utilizator dahaandreiDaha Andrei Codrin dahaandrei Data 23 noiembrie 2017 20:33:25
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <fstream>

using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

int n, m, q, x, y;
struct tree{
  int parent;
  int depth;
}v[100001];

int find_root(int i){
  int root = i, node = i, copy_i = i;

  while (v[node].parent != root)
    node = root = v[node].parent;

  node = i;
  while (v[node].parent != root){
    copy_i = node;
    node = v[node].parent;
    v[copy_i].parent = root;
    v[copy_i].depth = 0;
  }

  return root;
}

void union_trees(int i, int j){
  if (v[i].depth < v[j].depth)
    v[i].parent = j;
  if (v[j].depth < v[i].depth)
    v[j].parent = i;
  if (v[i].depth == v[j].depth){
    v[j].parent = i;
    v[j].depth += 1;
  }
}

void querry(int i, int j){
  int root_i = find_root(i);
  int root_j = find_root(j);

  if (root_i == root_j)
    out << "DA" << '\n';
  else
    out << "Nu" << '\n';
}

int main(){
  in >> n >> m;

  for (int i = 1; i <= n; ++ i){
    v[i].parent = i;
    v[i].depth = 0;
  }

  for (int i = 1; i <= m; ++ i){
    in >> q >> x >> y;
    if (q == 1)
      union_trees(x, y);
    else
      querry(x, y);
  }

  return 0;
}