#include #include #include #include #include #include #include #include #include // Maximum-cardinality matching in an undirected general graph. // // Micali--Vazirani shortest-augmenting-path phases (MIN/MAX with DDFS). // This version is based directly on the supplied GeneralMatchingMV code. // // Vertices are 0, ..., n-1. Self-loops are ignored. Parallel edges are // accepted. An initial matching is not fixed: augmentations may replace any // of its edges. // // Conservative complexity bound with ordinary union-find for petals: // O((n + m) sqrt(n) alpha(n)) time and O(n + m) memory. class GeneralMatchingMV { public: enum class InitialMatchingPolicy : unsigned char { // Keep every supplied matched pair, then greedily add edges between // currently exposed vertices before running MV phases. kGreedyExtend, // Start from exactly the supplied matching. This also supports a // non-maximal initial matching; the first phase may augment length-1 // paths. kUseAsIs, }; explicit GeneralMatchingMV(int n) : n_(n), graph_(safe_size(n)), mate_(safe_size(n), -1) { if (n < 0) throw std::invalid_argument("negative vertex count"); } void reserve_edges(std::size_t edge_count) { if (edge_count > static_cast(std::numeric_limits::max())) { throw std::length_error("too many edges for int edge ids"); } edge_state_.reserve(edge_count); } void reserve_degree(int vertex, std::size_t degree) { check_vertex(vertex); graph_[vertex].reserve(degree); } void add_edge(int u, int v) { check_vertex(u); check_vertex(v); if (u == v) return; if (edge_state_.size() >= static_cast(std::numeric_limits::max())) { throw std::length_error("too many edges for int edge ids"); } const int edge_id = static_cast(edge_state_.size()); if (graph_[u].empty()) ++active_vertex_count_; if (graph_[v].empty()) ++active_vertex_count_; graph_[u].push_back(HalfEdge{v, edge_id}); graph_[v].push_back(HalfEdge{u, edge_id}); edge_state_.push_back(0); } // Computes a maximum matching from scratch. int solve() { std::fill(mate_.begin(), mate_.end(), -1); matching_size_ = greedy_extend_matching(); return finish_solve(); } // Computes a maximum matching starting from initial_mate. // // initial_mate[v] is -1 or the mate of v. The checked overload verifies // range, symmetry, vertex-disjointness, and existence of every supplied // matched edge. Invalid input throws std::invalid_argument. int solve(const std::vector& initial_mate, InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) { if (!is_valid_initial_matching(initial_mate)) { throw std::invalid_argument("invalid initial matching"); } return solve_unchecked(initial_mate, policy); } // Same operation without validation. The caller must satisfy the contract // documented on solve(initial_mate, ...). int solve_unchecked( const std::vector& initial_mate, InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) { assert(static_cast(initial_mate.size()) == n_); if (&initial_mate != &mate_) mate_ = initial_mate; matching_size_ = matching_cardinality(mate_); if (policy == InitialMatchingPolicy::kGreedyExtend) { matching_size_ += greedy_extend_matching(); } return finish_solve(); } // Convenience overload for a list of disjoint matched endpoint pairs. int solve_from_matching_edges( const std::vector>& initial_edges, InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) { std::vector initial_mate(safe_size(n_), -1); for (const auto& [u, v] : initial_edges) { if (u < 0 || u >= n_ || v < 0 || v >= n_ || u == v || initial_mate[u] != -1 || initial_mate[v] != -1) { throw std::invalid_argument("invalid initial matching edges"); } initial_mate[u] = v; initial_mate[v] = u; } return solve(initial_mate, policy); } [[nodiscard]] bool is_valid_initial_matching( const std::vector& initial_mate) const { if (static_cast(initial_mate.size()) != n_) return false; for (int v = 0; v < n_; ++v) { const int u = initial_mate[v]; if (u == -1) continue; if (u < 0 || u >= n_ || u == v || initial_mate[u] != v) { return false; } if (v < u && !has_edge(v, u)) return false; } return true; } [[nodiscard]] int matching_size() const noexcept { return matching_size_; } // mate[v] == -1 iff v is exposed; otherwise mate[mate[v]] == v. [[nodiscard]] const std::vector& mate() const noexcept { return mate_; } [[nodiscard]] std::vector> matching_edges() const { std::vector> result; result.reserve(static_cast(matching_size_)); for (int v = 0; v < n_; ++v) { if (mate_[v] > v) result.emplace_back(v, mate_[v]); } return result; } private: static constexpr int INF = 1'000'000'000; static constexpr std::uint32_t EDGE_TYPE_MASK = 3U; enum class EdgeType : unsigned char { unscanned = 0, prop = 1, bridge = 2 }; struct HalfEdge { int to; int edge_id; }; // Petal disjoint-set structure. representative(v) is the current bud of v's // maximal petal. direct_parent records the non-compressed petal forest used // while opening petals during path reconstruction. struct PetalDSU { std::vector parent; std::vector size; std::vector group_root; std::vector direct_parent; void reset(int n) { const std::size_t count = static_cast(n); parent.resize(count); std::iota(parent.begin(), parent.end(), 0); size.assign(count, 1); group_root.resize(count); std::iota(group_root.begin(), group_root.end(), 0); direct_parent.assign(count, -1); } int find(int v) { while (parent[v] != v) { parent[v] = parent[parent[v]]; v = parent[v]; } return v; } int representative(int v) { return group_root[find(v)]; } // Merges the current petal rooted at a into the current petal rooted at b; // the resulting bud is the old bud of b. void link_to(int a, int b) { assert(direct_parent[a] == -1); assert(direct_parent[b] == -1); direct_parent[a] = b; int ra = find(a); int rb = find(b); assert(ra != rb); const int resulting_bud = group_root[rb]; if (size[ra] < size[rb]) { parent[ra] = rb; size[rb] += size[ra]; group_root[rb] = resulting_bud; } else { parent[rb] = ra; size[ra] += size[rb]; group_root[ra] = resulting_bud; } } }; struct BridgeInfo { int endpoint0 = -1; int endpoint1 = -1; int bud0 = -1; int bud1 = -1; }; struct ReconstructionTask { enum class Kind : unsigned char { augment, augment_initial, open_petal, install_edge, }; Kind kind; int first; int second; int third; static ReconstructionTask augment(int u, int target, bool initial) { return ReconstructionTask{ initial ? Kind::augment_initial : Kind::augment, u, target, -1, }; } static ReconstructionTask open_petal(int original, int bud, int target_bud) { return ReconstructionTask{Kind::open_petal, original, bud, target_bud}; } static ReconstructionTask install_edge(int u, int v) { return ReconstructionTask{Kind::install_edge, u, v, -1}; } }; struct OpeningFrame { int original; int bud; int next_child; }; int n_; std::vector> graph_; std::vector edge_state_; int active_vertex_count_ = 0; std::uint32_t phase_token_ = 0; bool phase_storage_ready_ = false; std::vector mate_; int matching_size_ = 0; std::vector> predecessors_; std::vector ddfs_predecessor_cursor_; std::vector removed_; std::vector even_level_; std::vector odd_level_; PetalDSU petal_; int next_color_ = 1; std::vector color_; // For a DDFS-tree arc: (original predecessor vertex, its bud when inserted). std::vector>> ddfs_children_; std::vector bridge_of_; std::vector bridge_phase_; // A vector + read cursor is faster and more allocation-friendly than // std::queue/deque for this append-only phase queue. std::vector removed_queue_; std::size_t removed_queue_head_ = 0; // Phase and reconstruction scratch storage. Capacities are retained between // phases to avoid repeated allocation on hard instances. std::vector> vertices_at_level_; std::vector>> bridges_by_tenacity_; std::vector removed_predecessor_count_; std::vector ddfs_stack0_; std::vector ddfs_stack1_; std::vector ddfs_support_; std::vector reconstruction_tasks_; std::vector opening_path_; // Only buckets used in the previous phase are cleared. This avoids touching // O(n) vector objects for each bucket family on sparse/easy phases. std::vector touched_predecessors_; std::vector touched_ddfs_children_; std::vector touched_levels_; std::vector touched_tenacities_; static std::size_t safe_size(int n) noexcept { return n < 0 ? 0U : static_cast(n); } void check_vertex(int v) const { if (v < 0 || v >= n_) throw std::out_of_range("vertex id out of range"); } [[nodiscard]] bool has_edge(int u, int v) const { for (const HalfEdge& edge : graph_[u]) { if (edge.to == v) return true; } return false; } static int matching_cardinality(const std::vector& mate) { int result = 0; for (int v = 0; v < static_cast(mate.size()); ++v) { result += (mate[v] > v); } return result; } int finish_solve() { const int trivial_upper_bound = active_vertex_count_ / 2; while (matching_size_ < trivial_upper_bound) { reset_phase(); const int augmented_paths = run_phase(); if (augmented_paths == 0) break; matching_size_ += augmented_paths; } #ifndef NDEBUG verify_matching(); assert(matching_size_ == matching_cardinality(mate_)); #endif return matching_size_; } int greedy_extend_matching() { int added = 0; for (int u = 0; u < n_; ++u) { if (mate_[u] != -1) continue; for (const HalfEdge& edge : graph_[u]) { const int v = edge.to; if (mate_[v] == -1) { mate_[u] = v; mate_[v] = u; ++added; break; } } } return added; } [[nodiscard]] int min_level(int v) const { return std::min(even_level_[v], odd_level_[v]); } [[nodiscard]] int tenacity(int u, int v) const { if (mate_[u] == v) return odd_level_[u] + odd_level_[v] + 1; return even_level_[u] + even_level_[v] + 1; } [[nodiscard]] EdgeType edge_type(int edge_id) const noexcept { const std::uint32_t state = edge_state_[edge_id]; if ((state & ~EDGE_TYPE_MASK) != phase_token_) { return EdgeType::unscanned; } return static_cast(state & EDGE_TYPE_MASK); } void set_edge_type(int edge_id, EdgeType type) noexcept { edge_state_[edge_id] = phase_token_ | static_cast(type); } template static void clear_touched_buckets(std::vector>& buckets, std::vector& touched) { for (const int index : touched) buckets[index].clear(); touched.clear(); } void push_predecessor(int vertex, int predecessor) { auto& bucket = predecessors_[vertex]; if (bucket.empty()) touched_predecessors_.push_back(vertex); bucket.push_back(predecessor); } void push_ddfs_child(int vertex, int original, int bud) { auto& bucket = ddfs_children_[vertex]; if (bucket.empty()) touched_ddfs_children_.push_back(vertex); bucket.emplace_back(original, bud); } void set_level(int vertex, int level) { assert(0 <= level && level < n_); if (level & 1) { odd_level_[vertex] = level; } else { even_level_[vertex] = level; } auto& bucket = vertices_at_level_[level]; if (bucket.empty()) touched_levels_.push_back(level); bucket.push_back(vertex); } void push_bridge(int tenacity_value, int u, int v) { assert(0 <= tenacity_value && tenacity_value < static_cast(bridges_by_tenacity_.size())); auto& bucket = bridges_by_tenacity_[tenacity_value]; if (bucket.empty()) touched_tenacities_.push_back(tenacity_value); bucket.emplace_back(u, v); } void set_bridge_info(int vertex, const BridgeInfo& bridge) noexcept { bridge_of_[vertex] = bridge; bridge_phase_[vertex] = phase_token_; } void ensure_phase_storage() { if (phase_storage_ready_) return; const std::size_t count = safe_size(n_); predecessors_.resize(count); ddfs_predecessor_cursor_.assign(count, 0); removed_.assign(count, 0); even_level_.assign(count, INF); odd_level_.assign(count, INF); color_.assign(count, 0); ddfs_children_.resize(count); bridge_of_.resize(count); bridge_phase_.assign(count, 0); vertices_at_level_.resize(count); bridges_by_tenacity_.resize(2 * count + 2); removed_predecessor_count_.assign(count, 0); phase_storage_ready_ = true; } void advance_phase_token() { constexpr std::uint32_t STEP = EDGE_TYPE_MASK + 1U; if (phase_token_ > std::numeric_limits::max() - STEP) { std::fill(edge_state_.begin(), edge_state_.end(), 0U); std::fill(bridge_phase_.begin(), bridge_phase_.end(), 0U); phase_token_ = STEP; } else { phase_token_ += STEP; } } void reset_phase() { ensure_phase_storage(); advance_phase_token(); clear_touched_buckets(predecessors_, touched_predecessors_); clear_touched_buckets(ddfs_children_, touched_ddfs_children_); clear_touched_buckets(vertices_at_level_, touched_levels_); clear_touched_buckets(bridges_by_tenacity_, touched_tenacities_); std::fill(ddfs_predecessor_cursor_.begin(), ddfs_predecessor_cursor_.end(), 0); std::fill(removed_.begin(), removed_.end(), 0); std::fill(even_level_.begin(), even_level_.end(), INF); std::fill(odd_level_.begin(), odd_level_.end(), INF); petal_.reset(n_); next_color_ = 1; std::fill(color_.begin(), color_.end(), 0); std::fill(removed_predecessor_count_.begin(), removed_predecessor_count_.end(), 0); ddfs_stack0_.clear(); ddfs_stack1_.clear(); ddfs_support_.clear(); reconstruction_tasks_.clear(); opening_path_.clear(); removed_queue_.clear(); removed_queue_head_ = 0; } // Advances one of the two coordinated DFS stacks by one elementary action. // Returns -1 if DDFS should continue, or the bottleneck bud otherwise. int ddfs_move(std::vector& stack0, int color0, std::vector& stack1, int color1, std::vector& support) { static_cast(color1); // Used by a debug-only invariant below. const int u = stack0.back(); int& cursor = ddfs_predecessor_cursor_[u]; while (cursor < static_cast(predecessors_[u].size())) { const int original_predecessor = predecessors_[u][cursor++]; const int v = petal_.representative(original_predecessor); assert(removed_[original_predecessor] == removed_[v]); if (removed_[original_predecessor]) continue; if (color_[v] == 0) { stack0.push_back(v); support.push_back(v); push_ddfs_child(u, original_predecessor, v); color_[v] = color0; return -1; } if (v == stack1.back()) { push_ddfs_child(u, original_predecessor, v); } } stack0.pop_back(); if (stack0.empty()) { if (stack1.size() == 1) { const int bottleneck = stack1.back(); color_[bottleneck] = 0; return bottleneck; } assert(color_[stack1.back()] == color1); stack0.push_back(stack1.back()); color_[stack0.back()] = color0; stack1.pop_back(); } return -1; } // Returns either two exposed roots reached by vertex-disjoint paths, or // (b, b), where b is the bottleneck/bud of the newly found petal. std::pair ddfs(int endpoint0, int endpoint1) { ddfs_stack0_.clear(); ddfs_stack1_.clear(); ddfs_support_.clear(); ddfs_stack0_.push_back(petal_.representative(endpoint0)); ddfs_stack1_.push_back(petal_.representative(endpoint1)); if (ddfs_stack0_.front() == ddfs_stack1_.front()) { return {ddfs_stack0_.front(), ddfs_stack0_.front()}; } ddfs_support_.push_back(ddfs_stack0_.front()); ddfs_support_.push_back(ddfs_stack1_.front()); const int color0 = color_[ddfs_stack0_.front()] = ++next_color_; const int color1 = color_[ddfs_stack1_.front()] = ++next_color_; assert(color0 == (color1 ^ 1)); while (true) { if (min_level(ddfs_stack0_.back()) == 0 && min_level(ddfs_stack1_.back()) == 0) { return {ddfs_stack0_.back(), ddfs_stack1_.back()}; } int bottleneck; if (min_level(ddfs_stack0_.back()) >= min_level(ddfs_stack1_.back())) { bottleneck = ddfs_move(ddfs_stack0_, color0, ddfs_stack1_, color1, ddfs_support_); } else { bottleneck = ddfs_move(ddfs_stack1_, color1, ddfs_stack0_, color0, ddfs_support_); } if (bottleneck != -1) return {bottleneck, bottleneck}; } } void mark_removed(int v) { if (removed_[v]) return; removed_[v] = 1; removed_queue_.push_back(v); } // Installs a previously unmatched edge of the augmenting path. Vertices // already claimed by another path in this phase are ignored. void install_matching_edge(int u, int v) { if (removed_[u] || removed_[v] || mate_[u] == v) return; mark_removed(u); mark_removed(v); mate_[u] = v; mate_[v] = u; } // Finds the same first admissible DDFS-tree path as the recursive opening // procedure, then schedules its operations in their original execution order. bool schedule_petal_opening(int current_original, int current_bud, int target_bud) { opening_path_.clear(); opening_path_.push_back(OpeningFrame{current_original, current_bud, 0}); while (!opening_path_.empty() && opening_path_.back().bud != target_bud) { OpeningFrame& frame = opening_path_.back(); const auto& children = ddfs_children_[frame.bud]; bool descended = false; while (frame.next_child < static_cast(children.size())) { const auto [next_original, next_bud] = children[frame.next_child++]; if (next_bud == target_bud || color_[next_bud] == color_[frame.bud]) { opening_path_.push_back( OpeningFrame{next_original, next_bud, 0}); descended = true; break; } } if (!descended) opening_path_.pop_back(); } if (opening_path_.empty()) return false; // The recursive order is: process the deepest node, then while // unwinding process a parent and install the connecting matching edge. // Tasks are pushed in reverse because the task vector is a stack. for (std::size_t i = 0; i + 1 < opening_path_.size(); ++i) { reconstruction_tasks_.push_back(ReconstructionTask::install_edge( opening_path_[i].bud, opening_path_[i + 1].original)); reconstruction_tasks_.push_back(ReconstructionTask::augment( opening_path_[i].original, opening_path_[i].bud, false)); } const OpeningFrame& deepest = opening_path_.back(); reconstruction_tasks_.push_back(ReconstructionTask::augment( deepest.original, deepest.bud, false)); return true; } // Reconstructs and augments a shortest augmenting path. An explicit task // stack is used so nested petals do not consume the C++ call stack. void augment_path(int start, int target, bool initial = false) { reconstruction_tasks_.clear(); reconstruction_tasks_.push_back( ReconstructionTask::augment(start, target, initial)); while (!reconstruction_tasks_.empty()) { const ReconstructionTask task = reconstruction_tasks_.back(); reconstruction_tasks_.pop_back(); if (task.kind == ReconstructionTask::Kind::install_edge) { install_matching_edge(task.first, task.second); continue; } if (task.kind == ReconstructionTask::Kind::open_petal) { const bool opened = schedule_petal_opening( task.first, task.second, task.third); assert(opened); if (!opened) return; continue; } const bool is_initial = task.kind == ReconstructionTask::Kind::augment_initial; int u = task.first; const int current_target = task.second; if (u == current_target) continue; if (!is_initial && min_level(u) == even_level_[u]) { assert(!predecessors_[u].empty()); const int odd_vertex = predecessors_[u][0]; int index = 0; while (petal_.representative(predecessors_[odd_vertex][index]) != petal_.representative(odd_vertex)) { ++index; assert(index < static_cast(predecessors_[odd_vertex].size())); } u = predecessors_[odd_vertex][index]; assert(!removed_[u]); install_matching_edge(odd_vertex, u); reconstruction_tasks_.push_back(ReconstructionTask::augment( u, current_target, false)); continue; } assert(bridge_phase_[u] == phase_token_); const BridgeInfo bridge = bridge_of_[u]; int endpoint0 = bridge.endpoint0; int endpoint1 = bridge.endpoint1; int bud0 = bridge.bud0; int bud1 = bridge.bud1; assert(endpoint0 != -1 && endpoint1 != -1 && bud0 != -1 && bud1 != -1); if ((color_[bud0] ^ 1) == color_[u] || color_[bud1] == color_[u]) { std::swap(bud0, bud1); std::swap(endpoint0, endpoint1); } install_matching_edge(endpoint0, endpoint1); const int next_target = petal_.direct_parent[u]; assert(next_target != -1); // Desired order: open side 0, open side 1, continue above the petal. reconstruction_tasks_.push_back(ReconstructionTask::augment( next_target, current_target, false)); reconstruction_tasks_.push_back(ReconstructionTask::open_petal( endpoint1, bud1, next_target)); reconstruction_tasks_.push_back(ReconstructionTask::open_petal( endpoint0, bud0, u)); } } int run_phase() { for (int v = 0; v < n_; ++v) { if (mate_[v] == -1) set_level(v, 0); } int augmenting_path_count = 0; for (int level = 0; level < n_ && augmenting_path_count == 0; ++level) { for (const int u : vertices_at_level_[level]) { const bool odd_level_is_current = odd_level_[u] == level; for (const HalfEdge& edge : graph_[u]) { if (edge_type(edge.edge_id) != EdgeType::unscanned) continue; const bool edge_is_matched = mate_[u] == edge.to; if (odd_level_is_current != edge_is_matched) continue; const int neighbor_min_level = min_level(edge.to); if (neighbor_min_level >= level + 1) { set_edge_type(edge.edge_id, EdgeType::prop); if (neighbor_min_level > level + 1) { set_level(edge.to, level + 1); } push_predecessor(edge.to, u); } else { set_edge_type(edge.edge_id, EdgeType::bridge); const int t = tenacity(u, edge.to); if (t < INF) push_bridge(t, u, edge.to); } } } auto& current_bridges = bridges_by_tenacity_[2 * level + 1]; for (std::size_t bridge_index = 0; bridge_index < current_bridges.size(); ++bridge_index) { const auto [endpoint0, endpoint1] = current_bridges[bridge_index]; const int current_bud0 = petal_.representative(endpoint0); const int current_bud1 = petal_.representative(endpoint1); if (removed_[current_bud0] || removed_[current_bud1]) continue; const auto [root0, root1] = ddfs(endpoint0, endpoint1); const BridgeInfo bridge{endpoint0, endpoint1, petal_.representative(endpoint0), petal_.representative(endpoint1)}; // A pair of disjoint paths is represented as a temporary petal // whose bud is root1. This permits the same opening routine to // reconstruct both a true petal and an augmenting path. for (const int v : ddfs_support_) { if (v == root1) continue; set_bridge_info(v, bridge); petal_.link_to(v, root1); set_level(v, 2 * level + 1 - min_level(v)); if (even_level_[v] > odd_level_[v]) { for (const HalfEdge& edge : graph_[v]) { if (edge_type(edge.edge_id) == EdgeType::bridge && mate_[v] != edge.to) { const int t = tenacity(v, edge.to); if (t < INF) push_bridge(t, v, edge.to); } } } } if (root0 != root1) { augment_path(root0, root1, true); ++augmenting_path_count; // Delete all vertices that can no longer lie on another // shortest augmenting path in this phase. while (removed_queue_head_ < removed_queue_.size()) { const int v = removed_queue_[removed_queue_head_++]; for (const HalfEdge& edge : graph_[v]) { if (edge_type(edge.edge_id) == EdgeType::prop && min_level(edge.to) > min_level(v) && !removed_[edge.to] && ++removed_predecessor_count_[edge.to] == static_cast( predecessors_[edge.to].size())) { mark_removed(edge.to); } } } } } } return augmenting_path_count; } #ifndef NDEBUG void verify_matching() const { assert(static_cast(mate_.size()) == n_); for (int v = 0; v < n_; ++v) { if (mate_[v] == -1) continue; assert(0 <= mate_[v] && mate_[v] < n_); assert(mate_[v] != v); assert(mate_[mate_[v]] == v); assert(has_edge(v, mate_[v])); } } #endif }; #include using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int L, R; cin >> L >> R; GeneralMatchingMV G(2 * L + R); for (int i = 0; i < L; i++) { G.add_edge(2 * i, 2 * i + 1); } for (int i = 0; i < 2 * L; i++) { int K; cin >> K; for (int j = 0; j < K; j++) { int V; cin >> V; V--; G.add_edge(i, 2 * L + V); } } G.solve(); cout << G.matching_size() << "\n"; }