.. _program_listing_file_src_algo_dsu.h: Program Listing for File dsu.h ============================== |exhale_lsh| :ref:`Return to documentation for file ` (``src/algo/dsu.h``) .. |exhale_lsh| unicode:: U+021B0 .. UPWARDS ARROW WITH TIP LEFTWARDS .. code-block:: cpp #pragma once #include #include namespace sota::algo { template class DSU { public: DSU(int m, int n) : _m(m), _n(n) { _parent = std::vector(n * m, -1); _size = std::vector(n * m, 0); _objects = std::vector(n * m, nullptr); } void push(int i, T object) { _parent[i] = i; _size[i] = 1; _objects[i] = object; } int rep(int i) { if (_parent[i] == i) { return i; } return _parent[i] = rep(_parent[i]); } void make_union(int i, int j) { if (!(0 <= j && j < _n * _m) || _parent[i] == -1 || _parent[j] == -1) { return; } int a = rep(i); int b = rep(j); if (a == b) { return; } if (_size[a] < _size[b]) { std::swap(a, b); } _parent[b] = a; _size[a] += _size[b]; } std::vector> groups() { std::map> m; for (int i = 0; i < _n * _m; ++i) { if (_parent[i] == -1) { continue; } m[_objects[rep(i)]].push_back(_objects[i]); } std::vector> res; for (auto [k, vec] : m) { res.push_back(vec); } return res; } private: std::vector _parent; std::vector _objects; std::vector _size; int _m; int _n; }; } // namespace sota::algo