自定义并查集模板.cpp 278 B

123456789101112131415
  1. int f[/*size*/];
  2. void init(int n) {
  3. for (int i = 1; i <= n; i++)
  4. f[i] = i;
  5. }
  6. int find(int x) {
  7. return (f[x] == x) ? x : (f[x] = find(f[x]));
  8. }
  9. void merge(int x, int y) {
  10. int fx = find(x), fy = find(y);
  11. f[fx] = fy;
  12. }
  13. bool query(int x, int y) {
  14. return find(x) == find(y);
  15. }