#include #include #include #include #include #include #include #include #include // Maximum-cardinality matching in a general undirected graph. // // Standalone STL port of the revised Gabow shortest-augmenting-path algorithm // by Mehlhorn--Nobahari. The public API accepts a valid partial matching, // uses it as the starting matching, and greedily extends it before phase one. // // References: // https://arxiv.org/abs/2603.22909 // https://people.mpi-inf.mpg.de/~mehlhorn/ // CompanionPageGenMatchingImplementation.html // // Let m0 be the number of non-loop edges and k the number of vertices incident // to a non-loop edge. With ordinary union-find, the running time is // O(n + m + m0 sqrt(k) alpha(k + 2)); memory usage is O(n + m). // Parallel edges are accepted. Self-loops are ignored by the solver. class GeneralMatchingRevised { public: struct Edge { int u; int v; }; enum class InitialMatchingPolicy : unsigned char { // Preserve the supplied pairs and greedily add exposed--exposed edges. // This is normally faster and is the default. kGreedyExtend, // Skip the greedy O(m) pass. The checked overload verifies maximality; // the unchecked overload treats maximality as a precondition. kAssumeMaximal, }; explicit GeneralMatchingRevised(int n) : n_(n) { if (n < 0) throw std::invalid_argument("negative number of vertices"); mate_original_.assign(static_cast(n), -1); } void reserve_edges(std::size_t m) { if (m > static_cast(std::numeric_limits::max())) { throw std::length_error("too many edges for int edge ids"); } input_edges_.reserve(m); } int add_edge(int u, int v) { check_vertex(u); check_vertex(v); if (input_edges_.size() >= static_cast(std::numeric_limits::max())) { throw std::length_error("too many edges for int edge ids"); } const int id = static_cast(input_edges_.size()); input_edges_.push_back({u, v}); graph_dirty_ = true; solved_ = false; return id; } int solve() { if (solved_ && !graph_dirty_) return matching_size_; return solve_impl(nullptr, InitialMatchingPolicy::kGreedyExtend, /*validate_initial=*/false); } // initial_mate[v] is v's partner, or -1. It must be symmetric, disjoint, // and every pair must be an input edge. int solve( const std::vector& initial_mate, InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) { return solve_impl(&initial_mate, policy, /*validate_initial=*/true); } // Trusted-input variant. Size and integer range are still checked to avoid // out-of-bounds access; symmetry, disjointness, edge existence, and (when // requested) maximality are preconditions. int solve_unchecked( const std::vector& initial_mate, InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) { return solve_impl(&initial_mate, policy, /*validate_initial=*/false); } int solve_from_matching_edges( const std::vector>& initial_matching, InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) { std::vector initial_mate(static_cast(n_), -1); for (const auto& edge : initial_matching) { const int u = edge.first; const int v = edge.second; check_vertex(u); check_vertex(v); if (u == v || initial_mate[u] != -1 || initial_mate[v] != -1) { throw std::invalid_argument( "initial matching contains a loop or repeated vertex"); } initial_mate[u] = v; initial_mate[v] = u; } return solve(initial_mate, policy); } int size() const { require_solved(); return matching_size_; } const std::vector& mate() const { require_solved(); return mate_original_; } std::vector> matching_edges() const { require_solved(); std::vector> answer; answer.reserve(static_cast(matching_size_)); for (int v = 0; v < n_; ++v) { if (mate_original_[v] > v) { answer.emplace_back(v, mate_original_[v]); } } return answer; } std::vector matching_edge_ids() const { require_solved(); std::vector answer; answer.reserve(static_cast(matching_size_)); for (int v = 0; v < static_cast(mate_.size()); ++v) { if (mate_[v] > v) { assert(mate_edge_[v] != -1); answer.push_back(edges_[mate_edge_[v]].original_id); } } return answer; } const std::vector& edges() const noexcept { return input_edges_; } private: enum class Label : unsigned char { kEven, kOdd, kUnlabeled }; struct CompactEdge { int u; int v; int original_id; }; struct HdfsFrame { int h_vertex; int original_vertex; std::size_t adjacency_index; }; struct PathTask { enum class Kind : unsigned char { kVisit, kAppend } kind; int a; int b; }; // Union-find with an explicitly designated representative for every block. class RepresentativeDsu { public: void reset(int n) { parent_.assign(static_cast(n), -1); representative_.resize(static_cast(n)); std::iota(representative_.begin(), representative_.end(), 0); } int root(int x) { int r = x; while (parent_[r] >= 0) r = parent_[r]; while (x != r) { const int p = parent_[x]; parent_[x] = r; x = p; } return r; } int representative(int x) { return representative_[root(x)]; } void unite(int a, int b) { int ra = root(a); int rb = root(b); if (ra == rb) return; if (parent_[ra] > parent_[rb]) std::swap(ra, rb); parent_[ra] += parent_[rb]; parent_[rb] = ra; // The representative is intentionally unspecified until make_rep(). } void unite_keep(int a, int b, int designated_representative) { unite(a, b); make_rep(designated_representative); } void make_rep(int v) { representative_[root(v)] = v; } private: std::vector parent_; std::vector representative_; }; class BucketQueue { public: void reset(int max_key, std::size_t reserve_hint) { head_.assign(static_cast(max_key + 1), -1); nodes_.clear(); if (nodes_.capacity() < reserve_hint) nodes_.reserve(reserve_hint); } void push(int key, int edge_id) { if (key < 0 || key >= static_cast(head_.size())) return; const int node = static_cast(nodes_.size()); nodes_.push_back({edge_id, head_[key]}); head_[key] = node; } int pop(int key) { if (key < 0 || key >= static_cast(head_.size())) return -1; const int node = head_[key]; if (node == -1) return -1; head_[key] = nodes_[node].next; return nodes_[node].edge_id; } private: struct Node { int edge_id; int next; }; std::vector head_; std::vector nodes_; }; int n_; std::vector input_edges_; std::vector mate_original_; int matching_size_ = 0; bool solved_ = false; bool graph_dirty_ = true; // Compacted graph. Isolated vertices and vertices incident only to loops // are excluded from the internal algorithm. std::vector original_to_compact_; std::vector compact_to_original_; std::vector edges_; // CSR incidence lists. Every non-loop edge appears exactly twice. std::vector adjacency_offset_; std::vector adjacency_edge_; // Matching and Part I. std::vector mate_; std::vector mate_edge_; RepresentativeDsu base_; RepresentativeDsu delayed_base_; std::vector parent_; std::vector parent_edge_g_; std::vector source_bridge_; std::vector target_bridge_; std::vector bridge_edge_g_; std::vector path_mark_left_; std::vector path_mark_right_; std::uint64_t path_stamp_ = 0; std::vector