結果
| 問題 | No.3863 Almost Bipartite Matching |
| コンテスト | |
| ユーザー |
miscalc
|
| 提出日時 | 2026-07-25 18:09:49 |
| 結果 |
WA
不安定
|
| 実行時間 | - |
| コード長 | 33,495 bytes |
| 記録 | |
| コンパイル時間 | 2,447 ms |
| コンパイル使用メモリ | 362,920 KB |
| 実行使用メモリ | 75,740 KB |
| 最終ジャッジ日時 | 2026-12-04 23:34:26 |
| 合計ジャッジ時間 | 39,954 ms |
|
ジャッジサーバーID (参考情報) |
judge2_0 / judge3_0 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | WA * 2 |
| other | WA * 58 |
ソースコード
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <numeric>
#include <stdexcept>
#include <utility>
#include <vector>
// 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<std::size_t>(n), -1);
}
void reserve_edges(std::size_t m) {
if (m > static_cast<std::size_t>(std::numeric_limits<int>::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::size_t>(std::numeric_limits<int>::max())) {
throw std::length_error("too many edges for int edge ids");
}
const int id = static_cast<int>(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<int>& 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<int>& initial_mate,
InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) {
return solve_impl(&initial_mate, policy, /*validate_initial=*/false);
}
int solve_from_matching_edges(
const std::vector<std::pair<int, int>>& initial_matching,
InitialMatchingPolicy policy = InitialMatchingPolicy::kGreedyExtend) {
std::vector<int> initial_mate(static_cast<std::size_t>(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<int>& mate() const {
require_solved();
return mate_original_;
}
std::vector<std::pair<int, int>> matching_edges() const {
require_solved();
std::vector<std::pair<int, int>> answer;
answer.reserve(static_cast<std::size_t>(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<int> matching_edge_ids() const {
require_solved();
std::vector<int> answer;
answer.reserve(static_cast<std::size_t>(matching_size_));
for (int v = 0; v < static_cast<int>(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<Edge>& 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<std::size_t>(n), -1);
representative_.resize(static_cast<std::size_t>(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<int> parent_;
std::vector<int> representative_;
};
class BucketQueue {
public:
void reset(int max_key, std::size_t reserve_hint) {
head_.assign(static_cast<std::size_t>(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<int>(head_.size())) return;
const int node = static_cast<int>(nodes_.size());
nodes_.push_back({edge_id, head_[key]});
head_[key] = node;
}
int pop(int key) {
if (key < 0 || key >= static_cast<int>(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<int> head_;
std::vector<Node> nodes_;
};
int n_;
std::vector<Edge> input_edges_;
std::vector<int> 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<int> original_to_compact_;
std::vector<int> compact_to_original_;
std::vector<CompactEdge> edges_;
// CSR incidence lists. Every non-loop edge appears exactly twice.
std::vector<std::size_t> adjacency_offset_;
std::vector<int> adjacency_edge_;
// Matching and Part I.
std::vector<int> mate_;
std::vector<int> mate_edge_;
RepresentativeDsu base_;
RepresentativeDsu delayed_base_;
std::vector<int> parent_;
std::vector<int> parent_edge_g_;
std::vector<int> source_bridge_;
std::vector<int> target_bridge_;
std::vector<int> bridge_edge_g_;
std::vector<std::uint64_t> path_mark_left_;
std::vector<std::uint64_t> path_mark_right_;
std::uint64_t path_stamp_ = 0;
std::vector<Label> label_;
std::vector<int> lcp_;
BucketQueue queue_;
int delta_ = 0;
std::vector<std::pair<int, int>> delayed_unions_;
std::vector<int> changed_lcp_vertex_;
std::vector<int> changed_lcp_value_;
// Auxiliary graph H and Part III.
std::vector<int> rep_;
std::vector<int> mate_h_;
std::vector<unsigned char> is_h_edge_;
// Intrusive lists of original vertices contracted into each H vertex.
std::vector<int> h_block_head_;
std::vector<int> h_block_next_;
std::vector<Label> label_h_;
std::vector<int> parent_edge_h_;
std::vector<int> even_time_h_;
std::vector<int> bridge_edge_h_;
std::vector<int> bridge_direction_h_;
int h_clock_ = 0;
// Reused iterative DFS/path-lifting buffers.
std::vector<HdfsFrame> h_dfs_stack_;
std::vector<int> h_blossom_endpoints_scratch_;
std::vector<int> h_blossom_odd_scratch_;
std::vector<PathTask> h_path_task_stack_;
std::vector<PathTask> g_path_task_stack_;
std::vector<int> h_path_scratch_;
std::vector<int> h_paths_flat_;
std::vector<std::size_t> h_path_offsets_;
std::vector<int> nonmatching_edge_ids_scratch_;
void check_vertex(int v) const {
if (v < 0 || v >= n_) throw std::out_of_range("vertex id out of range");
}
void require_solved() const {
if (!solved_) throw std::logic_error("solve() has not been called");
}
int opposite(int edge_id, int v) const {
const CompactEdge& e = edges_[edge_id];
assert(e.u == v || e.v == v);
return e.u ^ e.v ^ v;
}
void ensure_compact_graph() {
if (!graph_dirty_) return;
original_to_compact_.assign(static_cast<std::size_t>(n_), -1);
std::vector<unsigned char> active(static_cast<std::size_t>(n_), 0);
for (const Edge& e : input_edges_) {
if (e.u != e.v) {
active[e.u] = 1;
active[e.v] = 1;
}
}
compact_to_original_.clear();
compact_to_original_.reserve(static_cast<std::size_t>(n_));
for (int v = 0; v < n_; ++v) {
if (!active[v]) continue;
original_to_compact_[v] =
static_cast<int>(compact_to_original_.size());
compact_to_original_.push_back(v);
}
const int k = static_cast<int>(compact_to_original_.size());
edges_.clear();
edges_.reserve(input_edges_.size());
std::vector<std::size_t> degree(static_cast<std::size_t>(k), 0);
for (int original_id = 0;
original_id < static_cast<int>(input_edges_.size()); ++original_id) {
const Edge& e = input_edges_[original_id];
if (e.u == e.v) continue;
const int u = original_to_compact_[e.u];
const int v = original_to_compact_[e.v];
edges_.push_back({u, v, original_id});
++degree[u];
++degree[v];
}
adjacency_offset_.assign(static_cast<std::size_t>(k) + 1U, 0);
for (int v = 0; v < k; ++v) {
adjacency_offset_[static_cast<std::size_t>(v) + 1U] =
adjacency_offset_[v] + degree[v];
}
adjacency_edge_.assign(adjacency_offset_.back(), -1);
std::vector<std::size_t> cursor = adjacency_offset_;
for (int id = 0; id < static_cast<int>(edges_.size()); ++id) {
const CompactEdge& e = edges_[id];
adjacency_edge_[cursor[e.u]++] = id;
adjacency_edge_[cursor[e.v]++] = id;
}
graph_dirty_ = false;
}
void initialize_storage(int k) {
const std::size_t ks = static_cast<std::size_t>(k);
const std::size_t ms = edges_.size();
mate_.assign(ks, -1);
mate_edge_.assign(ks, -1);
parent_.assign(ks, -1);
parent_edge_g_.assign(ks, -1);
source_bridge_.assign(ks, -1);
target_bridge_.assign(ks, -1);
bridge_edge_g_.assign(ks, -1);
path_mark_left_.assign(ks, 0);
path_mark_right_.assign(ks, 0);
path_stamp_ = 0;
label_.assign(ks, Label::kUnlabeled);
lcp_.assign(ks, 0);
rep_.assign(ks, -1);
mate_h_.assign(ks, -1);
is_h_edge_.assign(ms, 0);
h_block_head_.assign(ks, -1);
h_block_next_.assign(ks, -1);
label_h_.assign(ks, Label::kUnlabeled);
parent_edge_h_.assign(ks, -1);
even_time_h_.assign(ks, -1);
bridge_edge_h_.assign(ks, -1);
bridge_direction_h_.assign(ks, 0);
delayed_unions_.clear();
changed_lcp_vertex_.clear();
changed_lcp_value_.clear();
delayed_unions_.reserve(ks * 2U);
changed_lcp_vertex_.reserve(ks);
changed_lcp_value_.reserve(ks);
if (h_dfs_stack_.capacity() < ks) h_dfs_stack_.reserve(ks);
if (h_blossom_endpoints_scratch_.capacity() < ks) {
h_blossom_endpoints_scratch_.reserve(ks);
}
if (h_blossom_odd_scratch_.capacity() < ks) {
h_blossom_odd_scratch_.reserve(ks);
}
if (h_path_task_stack_.capacity() < ks) h_path_task_stack_.reserve(ks);
if (g_path_task_stack_.capacity() < ks) g_path_task_stack_.reserve(ks);
if (h_path_scratch_.capacity() < ks) h_path_scratch_.reserve(ks);
if (h_paths_flat_.capacity() < ks) h_paths_flat_.reserve(ks);
if (h_path_offsets_.capacity() < ks / 2U + 2U) {
h_path_offsets_.reserve(ks / 2U + 2U);
}
if (nonmatching_edge_ids_scratch_.capacity() < ks) {
nonmatching_edge_ids_scratch_.reserve(ks);
}
}
void install_initial_matching(const std::vector<int>* initial_mate,
bool validate_initial) {
const int k = static_cast<int>(compact_to_original_.size());
matching_size_ = 0;
if (initial_mate == nullptr) return;
if (static_cast<int>(initial_mate->size()) != n_) {
throw std::invalid_argument("initial mate array has the wrong size");
}
for (int v = 0; v < n_; ++v) {
const int u = (*initial_mate)[v];
if (u < -1 || u >= n_ || u == v) {
throw std::invalid_argument("invalid vertex in initial mate array");
}
if (validate_initial && u != -1 && (*initial_mate)[u] != v) {
throw std::invalid_argument("initial mate array is not symmetric");
}
}
for (int v = 0; v < n_; ++v) {
const int u = (*initial_mate)[v];
if (u == -1) continue;
const int cv = original_to_compact_[v];
const int cu = original_to_compact_[u];
if (cv == -1 || cu == -1) {
throw std::invalid_argument(
"initial matching uses a vertex with no non-loop input edge");
}
mate_[cv] = cu;
}
for (int v = 0; v < k; ++v) {
if (mate_[v] > v) ++matching_size_;
}
for (int id = 0; id < static_cast<int>(edges_.size()); ++id) {
const CompactEdge& e = edges_[id];
if (mate_[e.u] == e.v && mate_[e.v] == e.u &&
mate_edge_[e.u] == -1 && mate_edge_[e.v] == -1) {
mate_edge_[e.u] = mate_edge_[e.v] = id;
}
}
for (int v = 0; v < k; ++v) {
if (mate_[v] != -1 && mate_edge_[v] == -1) {
throw std::invalid_argument(
"initial matching contains a pair that is not an input edge");
}
}
}
void greedy_extend_matching() {
for (int id = 0; id < static_cast<int>(edges_.size()); ++id) {
const CompactEdge& e = edges_[id];
if (mate_[e.u] == -1 && mate_[e.v] == -1) {
mate_[e.u] = e.v;
mate_[e.v] = e.u;
mate_edge_[e.u] = mate_edge_[e.v] = id;
++matching_size_;
}
}
}
void validate_maximal_matching() const {
for (const CompactEdge& e : edges_) {
if (mate_[e.u] == -1 && mate_[e.v] == -1) {
throw std::invalid_argument(
"kAssumeMaximal was requested for a non-maximal matching");
}
}
}
int solve_impl(const std::vector<int>* initial_mate,
InitialMatchingPolicy policy, bool validate_initial) {
// Permit the natural warm-start idiom `matching.solve(matching.mate())`.
// The public result buffer is cleared below, so preserve it on aliasing.
std::vector<int> aliased_initial;
if (initial_mate == &mate_original_) {
aliased_initial = *initial_mate;
initial_mate = &aliased_initial;
}
solved_ = false;
ensure_compact_graph();
const int k = static_cast<int>(compact_to_original_.size());
mate_original_.assign(static_cast<std::size_t>(n_), -1);
if (k == 0) {
if (initial_mate != nullptr) {
if (static_cast<int>(initial_mate->size()) != n_) {
throw std::invalid_argument("initial mate array has the wrong size");
}
for (const int u : *initial_mate) {
if (u != -1) {
throw std::invalid_argument(
"nonempty initial matching in an edgeless graph");
}
}
}
matching_size_ = 0;
solved_ = true;
return 0;
}
initialize_storage(k);
install_initial_matching(initial_mate, validate_initial);
if (policy == InitialMatchingPolicy::kGreedyExtend) {
greedy_extend_matching();
} else if (validate_initial) {
validate_maximal_matching();
}
while (2 * matching_size_ < k) {
if (!phase_one()) break;
phase_two();
}
for (int v = 0; v < k; ++v) {
if (mate_[v] != -1) {
mate_original_[compact_to_original_[v]] =
compact_to_original_[mate_[v]];
}
}
solved_ = true;
return matching_size_;
}
int edge_weight(int edge_id) const {
const CompactEdge& e = edges_[edge_id];
return mate_edge_[e.u] == edge_id ? 2 : 0;
}
void scan_edge(int edge_id, int z) {
const int u = opposite(edge_id, z);
if (u == z || mate_[u] == z ||
label_[base_.representative(u)] == Label::kOdd) {
return;
}
if (label_[u] == Label::kUnlabeled) {
queue_.push(lcp_[z] + 2, edge_id);
} else {
queue_.push((lcp_[z] + lcp_[u]) / 2 + 1, edge_id);
}
}
void shrink_path(int blossom_base, int x, int y,
int blossom_bridge_edge) {
int v = base_.representative(x);
while (v != blossom_base) {
base_.unite_keep(v, blossom_base, blossom_base);
delayed_unions_.emplace_back(v, blossom_base);
v = mate_[v];
assert(v != -1);
base_.unite_keep(v, blossom_base, blossom_base);
delayed_unions_.emplace_back(v, blossom_base);
source_bridge_[v] = x;
target_bridge_[v] = y;
bridge_edge_g_[v] = blossom_bridge_edge;
changed_lcp_vertex_.push_back(v);
changed_lcp_value_.push_back(lcp_[v]);
lcp_[v] = lcp_[y] + lcp_[x] - lcp_[mate_[v]] + 2;
for (std::size_t i = adjacency_offset_[v];
i < adjacency_offset_[static_cast<std::size_t>(v) + 1U]; ++i) {
scan_edge(adjacency_edge_[i], v);
}
assert(parent_[v] != -1);
v = base_.representative(parent_[v]);
}
// End-of-blossom marker for delayed_base_.
delayed_unions_.emplace_back(blossom_base, blossom_base);
}
void restore_breakthrough_lcp_values() {
while (!changed_lcp_vertex_.empty()) {
const int v = changed_lcp_vertex_.back();
const int old_value = changed_lcp_value_.back();
changed_lcp_vertex_.pop_back();
changed_lcp_value_.pop_back();
lcp_[v] = old_value;
}
}
void apply_delayed_unions() {
for (const auto& operation : delayed_unions_) {
if (operation.first == operation.second) {
delayed_base_.make_rep(operation.first);
} else {
delayed_base_.unite(operation.first, operation.second);
}
}
delayed_unions_.clear();
}
void construct_h() {
const int k = static_cast<int>(mate_.size());
std::fill(h_block_head_.begin(), h_block_head_.end(), -1);
std::fill(mate_h_.begin(), mate_h_.end(), -1);
std::fill(is_h_edge_.begin(), is_h_edge_.end(), 0);
for (int v = 0; v < k; ++v) {
rep_[v] = delayed_base_.representative(v);
h_block_next_[v] = h_block_head_[rep_[v]];
h_block_head_[rep_[v]] = v;
}
for (int id = 0; id < static_cast<int>(edges_.size()); ++id) {
const CompactEdge& e = edges_[id];
const int u = e.u;
const int v = e.v;
const int uh = rep_[u];
const int vh = rep_[v];
const int weight = edge_weight(id);
if (uh == vh) continue;
if (label_[uh] == Label::kOdd && label_[vh] == Label::kOdd) continue;
const bool even_odd =
(label_[uh] == Label::kEven && label_[vh] == Label::kOdd &&
lcp_[v] == lcp_[u] + 1 - weight) ||
(label_[vh] == Label::kEven && label_[uh] == Label::kOdd &&
lcp_[u] == lcp_[v] + 1 - weight);
const bool unlabeled_unlabeled =
label_[uh] == Label::kUnlabeled &&
label_[vh] == Label::kUnlabeled && weight == 2;
const bool even_unlabeled =
(label_[uh] == Label::kEven &&
label_[vh] == Label::kUnlabeled && lcp_[u] == delta_ - 2) ||
(label_[vh] == Label::kEven &&
label_[uh] == Label::kUnlabeled && lcp_[v] == delta_ - 2);
const bool both_even =
label_[uh] == Label::kEven && label_[vh] == Label::kEven;
const bool even_even =
both_even &&
lcp_[u] + lcp_[v] == 2 * delta_ + weight - 2;
assert(!both_even || weight == 0);
if (even_odd || unlabeled_unlabeled || even_unlabeled || even_even) {
is_h_edge_[id] = 1;
if (weight == 2) {
mate_h_[uh] = vh;
mate_h_[vh] = uh;
}
}
}
}
bool phase_one() {
const int k = static_cast<int>(mate_.size());
delta_ = 0;
queue_.reset(k + 2, edges_.size());
base_.reset(k);
delayed_base_.reset(k);
delayed_unions_.clear();
std::fill(parent_edge_g_.begin(), parent_edge_g_.end(), -1);
std::fill(bridge_edge_g_.begin(), bridge_edge_g_.end(), -1);
for (int v = 0; v < k; ++v) {
label_[v] = mate_[v] == -1 ? Label::kEven : Label::kUnlabeled;
if (mate_[v] == -1) lcp_[v] = 0;
}
for (int v = 0; v < k; ++v) {
if (label_[v] == Label::kEven) {
for (std::size_t i = adjacency_offset_[v];
i < adjacency_offset_[static_cast<std::size_t>(v) + 1U]; ++i) {
scan_edge(adjacency_edge_[i], v);
}
}
}
while (delta_ <= k + 1) {
changed_lcp_vertex_.clear();
changed_lcp_value_.clear();
while (true) {
const int edge_id = queue_.pop(delta_);
if (edge_id == -1) break;
int x = edges_[edge_id].u;
int y = edges_[edge_id].v;
if (label_[base_.representative(x)] != Label::kEven) {
std::swap(x, y);
}
const int bx = base_.representative(x);
const int by = base_.representative(y);
if (label_[bx] != Label::kEven || y == mate_[x] || bx == by ||
label_[by] == Label::kOdd) {
continue;
}
if (label_[by] == Label::kUnlabeled) {
const int z = mate_[y];
assert(z != -1);
lcp_[y] = lcp_[x] + 1;
lcp_[z] = lcp_[x] + 2;
parent_[z] = y;
parent_[y] = x;
parent_edge_g_[y] = edge_id;
label_[y] = Label::kOdd;
label_[z] = Label::kEven;
for (std::size_t i = adjacency_offset_[z];
i < adjacency_offset_[static_cast<std::size_t>(z) + 1U]; ++i) {
scan_edge(adjacency_edge_[i], z);
}
continue;
}
if (label_[by] != Label::kEven ||
lcp_[x] + lcp_[y] != 2 * delta_ - 2) {
continue;
}
++path_stamp_;
int hx = bx;
int hy = by;
path_mark_left_[hx] = path_stamp_;
path_mark_right_[hy] = path_stamp_;
while (path_mark_left_[hy] != path_stamp_ &&
path_mark_right_[hx] != path_stamp_ &&
(mate_[hx] != -1 || mate_[hy] != -1)) {
if (mate_[hx] != -1) {
hx = base_.representative(parent_[mate_[hx]]);
path_mark_left_[hx] = path_stamp_;
}
if (mate_[hy] != -1) {
hy = base_.representative(parent_[mate_[hy]]);
path_mark_right_[hy] = path_stamp_;
}
}
if (path_mark_left_[hy] == path_stamp_ ||
path_mark_right_[hx] == path_stamp_) {
const int blossom_base =
path_mark_left_[hy] == path_stamp_ ? hy : hx;
shrink_path(blossom_base, x, y, edge_id);
shrink_path(blossom_base, y, x, edge_id);
} else {
restore_breakthrough_lcp_values();
construct_h();
return true;
}
}
apply_delayed_unions();
++delta_;
}
return false;
}
int other_h_endpoint(int edge_id, int h_vertex) const {
const CompactEdge& e = edges_[edge_id];
const int a = rep_[e.u];
const int b = rep_[e.v];
assert(a == h_vertex || b == h_vertex);
return a == h_vertex ? b : a;
}
HdfsFrame make_hdfs_frame(int h_vertex) const {
const int first_vertex = h_block_head_[h_vertex];
const std::size_t first_edge =
first_vertex == -1 ? 0U : adjacency_offset_[first_vertex];
return {h_vertex, first_vertex, first_edge};
}
int find_augmenting_path_h(int start_h) {
h_dfs_stack_.clear();
h_dfs_stack_.push_back(make_hdfs_frame(start_h));
while (!h_dfs_stack_.empty()) {
HdfsFrame& frame = h_dfs_stack_.back();
const int vh = frame.h_vertex;
const int v = frame.original_vertex;
if (v == -1) {
h_dfs_stack_.pop_back();
continue;
}
if (frame.adjacency_index >=
adjacency_offset_[static_cast<std::size_t>(v) + 1U]) {
frame.original_vertex = h_block_next_[v];
if (frame.original_vertex != -1) {
frame.adjacency_index = adjacency_offset_[frame.original_vertex];
}
continue;
}
const int edge_id = adjacency_edge_[frame.adjacency_index++];
if (!is_h_edge_[edge_id]) continue;
const int other_original = opposite(edge_id, v);
const int uh = rep_[other_original];
if (mate_h_[vh] == uh) continue;
if (label_h_[uh] == Label::kUnlabeled) {
const int mate_uh = mate_h_[uh];
label_h_[uh] = Label::kOdd;
parent_edge_h_[uh] = edge_id;
if (mate_uh == -1) return uh;
label_h_[mate_uh] = Label::kEven;
even_time_h_[mate_uh] = h_clock_++;
h_dfs_stack_.push_back(make_hdfs_frame(mate_uh));
continue;
}
const int bh = delayed_base_.representative(vh);
int zh = delayed_base_.representative(uh);
if (even_time_h_[bh] >= even_time_h_[zh]) continue;
h_blossom_endpoints_scratch_.clear();
h_blossom_odd_scratch_.clear();
while (zh != bh) {
h_blossom_endpoints_scratch_.push_back(zh);
zh = mate_h_[zh];
assert(zh != -1);
h_blossom_endpoints_scratch_.push_back(zh);
// This is descendant-to-base order for now.
h_blossom_odd_scratch_.push_back(zh);
const int parent_edge = parent_edge_h_[zh];
assert(parent_edge != -1);
const int parent_h = other_h_endpoint(parent_edge, zh);
zh = delayed_base_.representative(parent_h);
}
for (const int node : h_blossom_endpoints_scratch_) {
delayed_base_.unite(node, bh);
}
delayed_base_.make_rep(bh);
const int direction = edges_[edge_id].v == v ? 1 : -1;
for (const int odd : h_blossom_odd_scratch_) {
bridge_edge_h_[odd] = edge_id;
bridge_direction_h_[odd] = direction;
}
// Recursive order is closest-to-base first. The scratch vector is
// descendant-to-base, so pushing in forward order puts the closest node
// on top of the explicit DFS stack.
for (const int odd : h_blossom_odd_scratch_) {
h_dfs_stack_.push_back(make_hdfs_frame(odd));
}
}
return -1;
}
void append_path_h(std::vector<int>& path, int start_h, int target_h) {
h_path_task_stack_.clear();
h_path_task_stack_.push_back(
{PathTask::Kind::kVisit, start_h, target_h});
while (!h_path_task_stack_.empty()) {
const PathTask task = h_path_task_stack_.back();
h_path_task_stack_.pop_back();
if (task.kind == PathTask::Kind::kAppend) {
path.push_back(task.a);
continue;
}
const int vh = task.a;
const int target = task.b;
if (vh == target) continue;
if (label_h_[vh] == Label::kEven) {
const int odd = mate_h_[vh];
assert(odd != -1);
const int edge_id = parent_edge_h_[odd];
assert(edge_id != -1);
h_path_task_stack_.push_back(
{PathTask::Kind::kVisit, other_h_endpoint(edge_id, odd), target});
h_path_task_stack_.push_back(
{PathTask::Kind::kAppend, edge_id, 0});
continue;
}
const int bridge = bridge_edge_h_[vh];
assert(bridge != -1);
const CompactEdge& e = edges_[bridge];
const int descendant_original =
bridge_direction_h_[vh] == 1 ? e.u : e.v;
const int ancestor_original =
bridge_direction_h_[vh] == 1 ? e.v : e.u;
h_path_task_stack_.push_back(
{PathTask::Kind::kVisit, rep_[ancestor_original], target});
h_path_task_stack_.push_back(
{PathTask::Kind::kAppend, bridge, 0});
h_path_task_stack_.push_back(
{PathTask::Kind::kVisit, rep_[descendant_original],
rep_[mate_h_[vh]]});
}
}
void append_path_g(std::vector<int>& path, int start_v,
int target_v) {
g_path_task_stack_.clear();
g_path_task_stack_.push_back(
{PathTask::Kind::kVisit, start_v, target_v});
while (!g_path_task_stack_.empty()) {
const PathTask task = g_path_task_stack_.back();
g_path_task_stack_.pop_back();
if (task.kind == PathTask::Kind::kAppend) {
path.push_back(task.a);
continue;
}
const int v = task.a;
const int target = task.b;
if (v == target) continue;
if (label_[v] == Label::kEven) {
const int mate_v = mate_[v];
assert(mate_v != -1 && parent_[mate_v] != -1);
const int edge_id = parent_edge_g_[mate_v];
assert(edge_id != -1);
g_path_task_stack_.push_back(
{PathTask::Kind::kVisit, parent_[mate_v], target});
g_path_task_stack_.push_back(
{PathTask::Kind::kAppend, edge_id, 0});
continue;
}
const int bridge_edge = bridge_edge_g_[v];
assert(bridge_edge != -1);
g_path_task_stack_.push_back(
{PathTask::Kind::kVisit, target_bridge_[v], target});
g_path_task_stack_.push_back(
{PathTask::Kind::kAppend, bridge_edge, 0});
g_path_task_stack_.push_back(
{PathTask::Kind::kVisit, source_bridge_[v], mate_[v]});
}
}
void augment_h_path(std::size_t first, std::size_t last) {
nonmatching_edge_ids_scratch_.clear();
for (std::size_t i = first; i < last; ++i) {
const int edge_id = h_paths_flat_[i];
const CompactEdge& e = edges_[edge_id];
nonmatching_edge_ids_scratch_.push_back(edge_id);
append_path_g(nonmatching_edge_ids_scratch_, e.u, rep_[e.u]);
append_path_g(nonmatching_edge_ids_scratch_, e.v, rep_[e.v]);
}
for (const int edge_id : nonmatching_edge_ids_scratch_) {
const CompactEdge& e = edges_[edge_id];
mate_[e.u] = e.v;
mate_[e.v] = e.u;
mate_edge_[e.u] = mate_edge_[e.v] = edge_id;
}
++matching_size_;
}
void phase_two() {
const int k = static_cast<int>(mate_.size());
std::fill(label_h_.begin(), label_h_.end(), Label::kUnlabeled);
std::fill(parent_edge_h_.begin(), parent_edge_h_.end(), -1);
std::fill(even_time_h_.begin(), even_time_h_.end(), -1);
std::fill(bridge_edge_h_.begin(), bridge_edge_h_.end(), -1);
h_clock_ = 0;
for (int v = 0; v < k; ++v) rep_[v] = delayed_base_.representative(v);
h_paths_flat_.clear();
h_path_offsets_.clear();
h_path_offsets_.push_back(0);
for (int vh = 0; vh < k; ++vh) {
if (vh != rep_[vh]) continue;
if (label_h_[vh] != Label::kUnlabeled || mate_h_[vh] != -1) continue;
label_h_[vh] = Label::kEven;
even_time_h_[vh] = h_clock_++;
const int exposed = find_augmenting_path_h(vh);
if (exposed == -1) continue;
const int last_edge = parent_edge_h_[exposed];
assert(last_edge != -1);
h_path_scratch_.clear();
h_path_scratch_.push_back(last_edge);
append_path_h(h_path_scratch_, other_h_endpoint(last_edge, exposed), vh);
h_paths_flat_.insert(h_paths_flat_.end(), h_path_scratch_.begin(),
h_path_scratch_.end());
h_path_offsets_.push_back(h_paths_flat_.size());
}
assert(h_path_offsets_.size() > 1);
for (std::size_t i = 1; i < h_path_offsets_.size(); ++i) {
augment_h_path(h_path_offsets_[i - 1], h_path_offsets_[i]);
}
}
};
using GeneralMatching = GeneralMatchingRevised;
#include <bits/stdc++.h>
using namespace std;
int main()
{
//ios_base::sync_with_stdio(false);
//cin.tie(0);
int L, R;
cin >> L >> R;
GeneralMatching 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);
}
}
vector<int> mate(2 * L + R, -1);
for (int i = 0; i < L; i++)
mate[2 * i] = 2 * i + 1, mate[2 * i + 1] = 2 * i;
//cout << G.solve(mate) << "\n";
}
miscalc