algorithm

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub gtnao/algorithm

:heavy_check_mark: test/aoj/dsl_1_a.test.cpp

Depends on

Code

#define PROBLEM                                                                \
  "https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/1/DSL_1_A"

#include <bits/stdc++.h>
using namespace std;

#include "../../src/structure/union_find_tree.hpp"

int main() {
  int n, q;
  cin >> n >> q;
  UnionFindTree uft(n);
  for (int i = 0; i < q; ++i) {
    int com, x, y;
    cin >> com >> x >> y;
    if (com == 0) {
      uft.unite(x, y);
    } else {
      cout << (uft.is_same(x, y) ? 1 : 0) << endl;
    }
  }
  return 0;
}
#line 1 "test/aoj/dsl_1_a.test.cpp"
#define PROBLEM                                                                \
  "https://onlinejudge.u-aizu.ac.jp/courses/library/3/DSL/1/DSL_1_A"

#include <bits/stdc++.h>
using namespace std;

#line 2 "src/structure/union_find_tree.hpp"

#line 4 "src/structure/union_find_tree.hpp"
using namespace std;

struct UnionFindTree {
private:
  int n;
  vector<int> parent, rank;

public:
  UnionFindTree(int n) : n(n), parent(n, -1), rank(n, 0) {}

  int root(int x) {
    if (parent[x] == -1) {
      return x;
    }
    return parent[x] = root(parent[x]);
  }

  void unite(int x, int y) {
    x = root(x);
    y = root(y);
    if (x == y) {
      return;
    }
    if (rank[x] < rank[y]) {
      swap(x, y);
    }
    if (rank[x] == rank[y]) {
      ++rank[x];
    }
    parent[y] = x;
  }

  bool is_same(int x, int y) { return root(x) == root(y); }

  vector<vector<int>> groups() {
    vector<vector<int>> ret(n);
    for (int i = 0; i < n; i++) {
      ret[root(i)].emplace_back(i);
    }
    ret.erase(remove_if(begin(ret), end(ret),
                        [&](const vector<int> &v) { return v.empty(); }),
              end(ret));
    return ret;
  }
};
#line 8 "test/aoj/dsl_1_a.test.cpp"

int main() {
  int n, q;
  cin >> n >> q;
  UnionFindTree uft(n);
  for (int i = 0; i < q; ++i) {
    int com, x, y;
    cin >> com >> x >> y;
    if (com == 0) {
      uft.unite(x, y);
    } else {
      cout << (uft.is_same(x, y) ? 1 : 0) << endl;
    }
  }
  return 0;
}
Back to top page