結果

問題 No.3863 Almost Bipartite Matching
コンテスト
ユーザー miscalc
提出日時 2026-07-25 18:19:00
結果
TLE  
(最新)
AC  
(最初)
実行時間 -
コード長 23,196 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 3,445 ms
コンパイル使用メモリ 369,000 KB
実行使用メモリ 508,040 KB
最終ジャッジ日時 2026-12-04 23:35:44
合計ジャッジ時間 77,012 ms
ジャッジサーバーID
(参考情報)
judge2_0 / judge6_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 52 TLE * 3 -- * 3
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <numeric>
#include <queue>
#include <utility>
#include <vector>

// Maximum-cardinality matching in an undirected general graph.
//
// Micali--Vazirani shortest-augmenting-path phases (MIN/MAX with DDFS).
// Reference: Vijay V. Vazirani, "A Proof of the MV Matching Algorithm",
// arXiv:2012.03582.
//
// The implementation uses ordinary union-by-size + path compression for petals,
// hence O((n + m) sqrt(n) alpha(n)) is a conservative bound. After isolated
// vertices are discarded, this is O(m sqrt(n) alpha(n)). Path reconstruction is
// iterative and does not consume the C++ call stack.
//
// Vertices are 0, ..., n-1. Self-loops are ignored. Parallel edges are allowed.
class GeneralMatchingMV {
public:
    explicit GeneralMatchingMV(int n)
        : n_(n), graph_(n >= 0 ? static_cast<std::size_t>(n) : 0),
          mate_(n >= 0 ? static_cast<std::size_t>(n) : 0, -1) {
        assert(n >= 0);
    }

    void add_edge(int u, int v) {
        assert(0 <= u && u < n_);
        assert(0 <= v && v < n_);
        if (u == v) return;
        const int iu = static_cast<int>(graph_[u].size());
        const int iv = static_cast<int>(graph_[v].size());
        graph_[u].push_back(HalfEdge{v, iv, EdgeType::unscanned});
        graph_[v].push_back(HalfEdge{u, iu, EdgeType::unscanned});
    }

    // Computes a maximum matching from scratch and returns its cardinality.
    int solve() {
        mate_.assign(n_, -1);
        int current_size = greedy_initialize();
        while (current_size < n_ / 2) {
            reset_phase();
            const int augmented_paths = run_phase();
            if (augmented_paths == 0) break;
            current_size += augmented_paths;
        }
#ifndef NDEBUG
        verify_matching();
        assert(current_size == matching_size());
#endif
        return current_size;
    }

    [[nodiscard]] int matching_size() const {
        int matched_vertices = 0;
        for (int v = 0; v < n_; ++v) matched_vertices += (mate_[v] != -1);
        return matched_vertices / 2;
    }

    // mate[v] == -1 iff v is exposed; otherwise mate[mate[v]] == v.
    [[nodiscard]] const std::vector<int>& mate() const { return mate_; }

    [[nodiscard]] std::vector<std::pair<int, int>> matching_edges() const {
        std::vector<std::pair<int, int>> result;
        result.reserve(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;

    enum class EdgeType : unsigned char { unscanned, prop, bridge };

    struct HalfEdge {
        int to;
        int reverse_index;
        EdgeType type;
    };

    // 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<int> parent;
        std::vector<int> size;
        std::vector<int> group_root;
        std::vector<int> direct_parent;

        void reset(int n) {
            parent.resize(n);
            std::iota(parent.begin(), parent.end(), 0);
            size.assign(n, 1);
            group_root.resize(n);
            std::iota(group_root.begin(), group_root.end(), 0);
            direct_parent.assign(n, -1);
        }

        int find(int v) {
            int r = v;
            while (parent[r] != r) r = parent[r];
            while (parent[v] != v) {
                const int p = parent[v];
                parent[v] = r;
                v = p;
            }
            return r;
        }

        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, open_petal, install_edge };

        Kind kind;
        int first;
        int second;
        int third;
        bool initial;

        static ReconstructionTask augment(int u, int target, bool is_initial) {
            return ReconstructionTask{Kind::augment, u, target, -1, is_initial};
        }

        static ReconstructionTask open_petal(int original, int bud, int target_bud) {
            return ReconstructionTask{Kind::open_petal, original, bud, target_bud,
                                      false};
        }

        static ReconstructionTask install_edge(int u, int v) {
            return ReconstructionTask{Kind::install_edge, u, v, -1, false};
        }
    };

    struct OpeningFrame {
        int original;
        int bud;
        std::size_t next_child;
    };

    int n_;
    std::vector<std::vector<HalfEdge>> graph_;
    std::vector<int> mate_;

    std::vector<std::vector<int>> predecessors_;
    std::vector<std::size_t> ddfs_predecessor_cursor_;
    std::vector<unsigned char> removed_;
    std::vector<int> even_level_;
    std::vector<int> odd_level_;
    PetalDSU petal_;

    int next_color_ = 1;
    std::vector<int> color_;
    // For a DDFS-tree arc: (original predecessor vertex, its bud when inserted).
    std::vector<std::vector<std::pair<int, int>>> ddfs_children_;
    std::vector<BridgeInfo> bridge_of_;
    std::queue<int> removed_queue_;

    // Phase and reconstruction scratch storage. Capacities are retained between
    // phases to avoid repeated allocation on hard instances.
    std::vector<std::vector<int>> vertices_at_level_;
    std::vector<std::vector<std::pair<int, int>>> bridges_by_tenacity_;
    std::vector<std::size_t> removed_predecessor_count_;
    std::vector<int> ddfs_stack0_;
    std::vector<int> ddfs_stack1_;
    std::vector<int> ddfs_support_;
    std::vector<ReconstructionTask> reconstruction_tasks_;
    std::vector<OpeningFrame> opening_path_;

    template <class T>
    static void resize_and_clear_buckets(std::vector<std::vector<T>>& buckets,
                                         std::size_t count) {
        if (buckets.size() != count) buckets.resize(count);
        for (auto& bucket : buckets) bucket.clear();
    }

    int greedy_initialize() {
        int matching_size = 0;
        for (int u = 0; u < n_; ++u) {
            if (mate_[u] != -1) continue;
            for (const auto& edge : graph_[u]) {
                const int v = edge.to;
                if (mate_[v] == -1) {
                    mate_[u] = v;
                    mate_[v] = u;
                    ++matching_size;
                    break;
                }
            }
        }
        return matching_size;
    }

    [[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;
    }

    void reset_phase() {
        for (auto& adjacency : graph_) {
            for (auto& edge : adjacency) edge.type = EdgeType::unscanned;
        }
        const std::size_t vertex_count = static_cast<std::size_t>(n_);
        resize_and_clear_buckets(predecessors_, vertex_count);
        ddfs_predecessor_cursor_.assign(vertex_count, 0);
        removed_.assign(vertex_count, 0);
        even_level_.assign(vertex_count, INF);
        odd_level_.assign(vertex_count, INF);
        petal_.reset(n_);
        next_color_ = 1;
        color_.assign(vertex_count, 0);
        resize_and_clear_buckets(ddfs_children_, vertex_count);
        bridge_of_.assign(vertex_count, {});
        resize_and_clear_buckets(vertices_at_level_, vertex_count);
        resize_and_clear_buckets(
            bridges_by_tenacity_, static_cast<std::size_t>(2 * n_ + 2));
        removed_predecessor_count_.assign(vertex_count, 0);
        ddfs_stack0_.clear();
        ddfs_stack1_.clear();
        ddfs_support_.clear();
        reconstruction_tasks_.clear();
        opening_path_.clear();
        while (!removed_queue_.empty()) removed_queue_.pop();
    }

    // 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<int>& stack0, int color0,
                  std::vector<int>& stack1, int color1,
                  std::vector<int>& support) {
        static_cast<void>(color1);  // Used by a debug-only invariant below.
        const int u = stack0.back();
        auto& cursor = ddfs_predecessor_cursor_[u];
        while (cursor < 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);
                ddfs_children_[u].emplace_back(original_predecessor, v);
                color_[v] = color0;
                return -1;
            }
            if (v == stack1.back()) {
                ddfs_children_[u].emplace_back(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<int, int> 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(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 < 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;
            }

            int u = task.first;
            const int current_target = task.second;
            if (u == current_target) continue;

            if (!task.initial && min_level(u) == even_level_[u]) {
                assert(!predecessors_[u].empty());
                const int odd_vertex = predecessors_[u][0];

                std::size_t index = 0;
                while (petal_.representative(predecessors_[odd_vertex][index]) !=
                       petal_.representative(odd_vertex)) {
                    ++index;
                    assert(index < 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;
            }

            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() {
        auto set_level = [&](int v, int level) {
            assert(0 <= level && level < n_);
            if (level & 1) {
                odd_level_[v] = level;
            } else {
                even_level_[v] = level;
            }
            vertices_at_level_[level].push_back(v);
        };

        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]) {
                for (auto& edge : graph_[u]) {
                    const bool correct_parity_edge =
                        ((odd_level_[u] == level) == (mate_[u] == edge.to));
                    if (edge.type != EdgeType::unscanned || !correct_parity_edge) continue;

                    if (min_level(edge.to) >= level + 1) {
                        edge.type = EdgeType::prop;
                        graph_[edge.to][edge.reverse_index].type = EdgeType::prop;
                        if (min_level(edge.to) > level + 1) set_level(edge.to, level + 1);
                        predecessors_[edge.to].push_back(u);
                    } else {
                        edge.type = EdgeType::bridge;
                        graph_[edge.to][edge.reverse_index].type = EdgeType::bridge;
                        const int t = tenacity(u, edge.to);
                        if (t < INF) {
                            assert(0 <= t && t < static_cast<int>(bridges_by_tenacity_.size()));
                            bridges_by_tenacity_[t].emplace_back(u, edge.to);
                        }
                    }
                }
            }

            for (const auto& [endpoint0, endpoint1] : bridges_by_tenacity_[2 * level + 1]) {
                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;
                    bridge_of_[v] = bridge;
                    petal_.link_to(v, root1);

                    set_level(v, 2 * level + 1 - min_level(v));
                    for (const auto& edge : graph_[v]) {
                        if (even_level_[v] > odd_level_[v] &&
                            edge.type == EdgeType::bridge && mate_[v] != edge.to) {
                            const int t = tenacity(v, edge.to);
                            if (t < INF) {
                                assert(0 <= t && t < static_cast<int>(bridges_by_tenacity_.size()));
                                bridges_by_tenacity_[t].emplace_back(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_.empty()) {
                        const int v = removed_queue_.front();
                        removed_queue_.pop();
                        for (const auto& edge : graph_[v]) {
                            if (edge.type == EdgeType::prop &&
                                min_level(edge.to) > min_level(v) &&
                                !removed_[edge.to] &&
                                ++removed_predecessor_count_[edge.to] ==
                                    predecessors_[edge.to].size()) {
                                mark_removed(edge.to);
                            }
                        }
                    }
                }
            }
        }
        return augmenting_path_count;
    }

#ifndef NDEBUG
    void verify_matching() const {
        assert(static_cast<int>(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);
            bool edge_exists = false;
            for (const auto& edge : graph_[v]) edge_exists |= (edge.to == mate_[v]);
            assert(edge_exists);
        }
    }
#endif
};

#include <bits/stdc++.h>
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";
}
0