Cod sursa(job #2527027)

Utilizator greenadexIulia Harasim greenadex Data 19 ianuarie 2020 15:07:58
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <string>
#include <vector>

const std::string kInputFileName = "disjoint.in";
const std::string kOutputFileName = "disjoint.out";

class DisjointSets {
public:
  explicit DisjointSets(int n) {
    father_.reserve(n);
    for (int i = 0; i < n; i++) {
      father_.push_back(i);
    }
  }

  void Unite(int x, int y) {
    int root_father_x = GetRootFather(x);
    int past_father;
    do {
      past_father = father_[y];
      father_[y] = root_father_x;
      y = past_father;
    } while (past_father != y);
  }

  bool AreInSameSet(int x, int y) {
    return GetRootFather(x) == GetRootFather(y);
  }

private:
  int GetRootFather(int x) {
    if (father_[x] == x) {
      return x;
    }
    int root_father = GetRootFather(father_[x]);
    father_[x] = root_father;
    return root_father;
  }

  std::vector<int> father_;
};


int main() {
  std::ifstream fin(kInputFileName);
  std::ofstream fout(kOutputFileName);

  int nums;
  fin >> nums;

  DisjointSets disjoint_sets(nums);

  int num_ops;
  fin >> num_ops;

  for (int i = 0; i < num_ops; i++) {
    int op_type, x, y;
    fin >> op_type >> x >> y;
    switch (op_type) {
      case 1:
        disjoint_sets.Unite(x - 1, y - 1);
        break;
      case 2:
        fout << (disjoint_sets.AreInSameSet(x - 1, y - 1) ? "DA" : "NU") << '\n';
        break;
      default:
        return -1;
    }
  }

  return 0;
}