logicaffeine_proof/matching.rs
1//! Certified bipartite-matching infeasibility — the polynomial reasoner for pigeonhole-shaped
2//! problems that are *exponential* for resolution (and therefore for any CDCL SAT solver, ours
3//! included).
4//!
5//! Many infeasibility claims are really "n items must each take a distinct slot, but they only
6//! reach m < n slots" — graph colouring of a clique (n mutually-adjacent movements need n phases),
7//! the pigeonhole principle, exam scheduling, register allocation. Encoded as boolean SAT these are
8//! pigeonhole instances, which need exponentially long resolution refutations. But the underlying
9//! question — does a system of "each slot holds at most one item" constraints admit an assignment
10//! of every item? — is just **bipartite maximum matching**, decided in polynomial time.
11//!
12//! [`assign_or_hall`] returns either a feasible assignment (a checkable witness of feasibility) or a
13//! **Hall witness**: a set `S` of items whose combined reachable slots `T` satisfy `|T| < |S|`, so
14//! the items cannot be placed (a checkable witness of *in*feasibility, à la a clique or an odd
15//! cycle). Both outcomes are independently re-verifiable — [`is_hall_witness`] and a feasibility
16//! check — so this is a *certified* decision, never a trusted solver verdict.
17
18/// The outcome of a bipartite "each slot holds at most one item" feasibility check.
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub enum MatchOutcome {
21 /// Every item placed: `assignment[i]` is the slot item `i` takes (all distinct).
22 Feasible(Vec<usize>),
23 /// No assignment exists, witnessed by a deficient set of items.
24 Infeasible(HallWitness),
25}
26
27/// A Hall-theorem certificate of infeasibility: `items` (the set `S`) can collectively reach only
28/// the slots in `slots` (a superset of `N(S)`), and `slots.len() < items.len()` — so by pigeonhole
29/// the items cannot be placed one-per-slot. Independently checkable via [`is_hall_witness`].
30#[derive(Clone, Debug, PartialEq, Eq)]
31pub struct HallWitness {
32 /// The deficient item set `S`.
33 pub items: Vec<usize>,
34 /// Slots covering `N(S)`, with `slots.len() < items.len()`.
35 pub slots: Vec<usize>,
36}
37
38/// Decide whether every item can be assigned a distinct slot, where `adj[i]` lists the slots item
39/// `i` may use and slots range over `0..num_slots`. Returns a perfect assignment or a certified
40/// Hall witness. Finds a **maximum** matching with **Hopcroft–Karp** (`O(E·√V)` — many shortest
41/// vertex-disjoint augmenting paths per phase, far faster than Kuhn's `O(V·E)` as instances grow),
42/// then — on failure — the König alternating-reachability construction extracts the deficient set.
43pub fn assign_or_hall(adj: &[Vec<usize>], num_slots: usize) -> MatchOutcome {
44 let n = adj.len();
45 // Counting fast-path: more items than slots is infeasible by pigeonhole alone — each slot holds
46 // at most one item, so `n` items demand `n` distinct slots and only `num_slots < n` exist. No
47 // matching needed; the whole item set against all slots is the Hall witness. O(n) instead of
48 // O(E·√V), so pure pigeonhole (the common case) is decided in microseconds at any scale.
49 if n > num_slots {
50 return MatchOutcome::Infeasible(HallWitness {
51 items: (0..n).collect(),
52 slots: (0..num_slots).collect(),
53 });
54 }
55 let mut slot_match: Vec<Option<usize>> = vec![None; num_slots]; // slot -> item
56 let mut item_match: Vec<Option<usize>> = vec![None; n]; // item -> slot
57 hopcroft_karp(adj, &mut slot_match, &mut item_match);
58 if item_match.iter().all(|m| m.is_some()) {
59 return MatchOutcome::Feasible(item_match.into_iter().map(|m| m.unwrap()).collect());
60 }
61 MatchOutcome::Infeasible(extract_hall(adj, num_slots, &slot_match, &item_match))
62}
63
64/// Hopcroft–Karp maximum bipartite matching. Each phase: a BFS layers the items by shortest
65/// alternating-path distance toward a free slot, then DFS augments along a maximal set of
66/// vertex-disjoint shortest paths — `O(√V)` phases of `O(E)`.
67fn hopcroft_karp(
68 adj: &[Vec<usize>],
69 slot_match: &mut [Option<usize>],
70 item_match: &mut [Option<usize>],
71) {
72 let n = adj.len();
73 let num_slots = slot_match.len();
74 const INF: usize = usize::MAX;
75 loop {
76 // BFS over items: dist[u] is u's layer; a phase exists iff a free slot becomes reachable.
77 let mut dist = vec![INF; n];
78 let mut queue = std::collections::VecDeque::new();
79 for u in 0..n {
80 if item_match[u].is_none() {
81 dist[u] = 0;
82 queue.push_back(u);
83 }
84 }
85 let mut reachable_free = false;
86 while let Some(u) = queue.pop_front() {
87 for &v in &adj[u] {
88 if v >= num_slots {
89 continue;
90 }
91 match slot_match[v] {
92 None => reachable_free = true,
93 Some(w) if dist[w] == INF => {
94 dist[w] = dist[u] + 1;
95 queue.push_back(w);
96 }
97 _ => {}
98 }
99 }
100 }
101 if !reachable_free {
102 break; // no augmenting path remains ⇒ the matching is maximum
103 }
104 for u in 0..n {
105 if item_match[u].is_none() {
106 hk_dfs(u, adj, slot_match, item_match, &mut dist);
107 }
108 }
109 }
110}
111
112/// One Hopcroft–Karp augmenting DFS, restricted to the BFS layering (`dist`). Dead ends are marked
113/// `INF` so other DFS calls in the same phase skip them, keeping the augmenting paths disjoint.
114fn hk_dfs(
115 u: usize,
116 adj: &[Vec<usize>],
117 slot_match: &mut [Option<usize>],
118 item_match: &mut [Option<usize>],
119 dist: &mut [usize],
120) -> bool {
121 let num_slots = slot_match.len();
122 for idx in 0..adj[u].len() {
123 let v = adj[u][idx];
124 if v >= num_slots {
125 continue;
126 }
127 let proceed = match slot_match[v] {
128 None => true,
129 Some(w) => dist[w] == dist[u] + 1 && hk_dfs(w, adj, slot_match, item_match, dist),
130 };
131 if proceed {
132 slot_match[v] = Some(u);
133 item_match[u] = Some(v);
134 return true;
135 }
136 }
137 dist[u] = usize::MAX;
138 false
139}
140
141/// König construction: alternating reachability from the unmatched items. Every reachable slot is
142/// matched (else an augmenting path would exist, contradicting maximality), and its matched item is
143/// reachable — so the reachable items outnumber the reachable slots by exactly the unmatched count,
144/// and every slot adjacent to a reachable item is itself reachable. Hence `S = reachable items`,
145/// `T = reachable slots` is a Hall witness with `N(S) ⊆ T` and `|T| < |S|`.
146fn extract_hall(
147 adj: &[Vec<usize>],
148 num_slots: usize,
149 slot_match: &[Option<usize>],
150 item_match: &[Option<usize>],
151) -> HallWitness {
152 let n = adj.len();
153 let mut item_reach = vec![false; n];
154 let mut slot_reach = vec![false; num_slots];
155 let mut stack: Vec<usize> = Vec::new();
156 for (u, m) in item_match.iter().enumerate() {
157 if m.is_none() {
158 item_reach[u] = true;
159 stack.push(u);
160 }
161 }
162 while let Some(u) = stack.pop() {
163 for &v in &adj[u] {
164 if v < num_slots && !slot_reach[v] {
165 slot_reach[v] = true;
166 if let Some(w) = slot_match[v] {
167 if !item_reach[w] {
168 item_reach[w] = true;
169 stack.push(w);
170 }
171 }
172 }
173 }
174 }
175 HallWitness {
176 items: (0..n).filter(|&u| item_reach[u]).collect(),
177 slots: (0..num_slots).filter(|&v| slot_reach[v]).collect(),
178 }
179}
180
181/// Independently re-check a Hall witness: every item in `S` reaches only slots in `T`, and
182/// `|T| < |S|`. This is the certificate verifier — a trusted, solver-free check that the claimed
183/// infeasibility is genuine.
184pub fn is_hall_witness(adj: &[Vec<usize>], w: &HallWitness) -> bool {
185 if w.items.len() <= w.slots.len() {
186 return false;
187 }
188 let slot_set: std::collections::HashSet<usize> = w.slots.iter().copied().collect();
189 w.items
190 .iter()
191 .all(|&i| i < adj.len() && adj[i].iter().all(|s| slot_set.contains(s)))
192}
193
194/// Re-check a feasible assignment: one distinct slot per item, each within that item's allowed set.
195pub fn is_valid_assignment(adj: &[Vec<usize>], num_slots: usize, assignment: &[usize]) -> bool {
196 if assignment.len() != adj.len() {
197 return false;
198 }
199 let mut used = vec![false; num_slots];
200 assignment.iter().enumerate().all(|(i, &s)| {
201 let ok = s < num_slots && adj[i].contains(&s) && !used[s];
202 if s < num_slots {
203 used[s] = true;
204 }
205 ok
206 })
207}
208
209// ── Capacitated b-matching (each slot holds up to a capacity) ────────────────
210
211/// The outcome of a capacitated assignment: each slot `s` holds at most `capacities[s]` items.
212#[derive(Clone, Debug, PartialEq, Eq)]
213pub enum CapMatchOutcome {
214 /// Every item placed: `assignment[i]` is the slot item `i` takes (respecting capacities).
215 Feasible(Vec<usize>),
216 /// No assignment exists, witnessed by a capacity-deficient item set.
217 Infeasible(CapHallWitness),
218}
219
220/// A capacitated Hall certificate: the items in `S` can only reach the slots in `slots`, whose
221/// *total capacity* is strictly less than `|S|` — so they cannot all be placed. Re-checkable via
222/// [`is_cap_hall_witness`].
223#[derive(Clone, Debug, PartialEq, Eq)]
224pub struct CapHallWitness {
225 /// The deficient item set `S`.
226 pub items: Vec<usize>,
227 /// Slots covering `N(S)`, with `Σ capacities[s] < |S|`.
228 pub slots: Vec<usize>,
229}
230
231/// Decide whether every item can be assigned a slot when slot `s` holds at most `capacities[s]`
232/// items (a b-matching / resource-allocation feasibility — e.g. traffic movements sharing
233/// capacity-limited green windows). Reduces to plain matching by splitting each slot into that many
234/// interchangeable copies, then maps the result (and any Hall witness) back to original slots.
235pub fn assign_or_hall_capacitated(adj: &[Vec<usize>], capacities: &[usize]) -> CapMatchOutcome {
236 let num_slots = capacities.len();
237 let mut offset = vec![0usize; num_slots + 1];
238 for s in 0..num_slots {
239 offset[s + 1] = offset[s] + capacities[s];
240 }
241 let total = offset[num_slots];
242 // Each item, adjacent to slot s, is adjacent to all of slot s's copies.
243 let exp_adj: Vec<Vec<usize>> = adj
244 .iter()
245 .map(|slots| {
246 slots
247 .iter()
248 .filter(|&&s| s < num_slots)
249 .flat_map(|&s| offset[s]..offset[s + 1])
250 .collect()
251 })
252 .collect();
253 let copy_to_slot = |c: usize| offset.partition_point(|&o| o <= c) - 1;
254 match assign_or_hall(&exp_adj, total) {
255 MatchOutcome::Feasible(copy_assign) => {
256 CapMatchOutcome::Feasible(copy_assign.into_iter().map(copy_to_slot).collect())
257 }
258 MatchOutcome::Infeasible(w) => {
259 // Reachable copies are exactly all copies of the reachable original slots, so their
260 // total capacity equals |w.slots| < |w.items| — the capacitated Hall deficiency.
261 let mut slots: Vec<usize> = w.slots.into_iter().map(copy_to_slot).collect();
262 slots.sort_unstable();
263 slots.dedup();
264 CapMatchOutcome::Infeasible(CapHallWitness {
265 items: w.items,
266 slots,
267 })
268 }
269 }
270}
271
272/// Re-check a capacitated Hall witness: every item in `S` reaches only slots in `T`, and the total
273/// capacity of `T` is below `|S|`.
274pub fn is_cap_hall_witness(adj: &[Vec<usize>], capacities: &[usize], w: &CapHallWitness) -> bool {
275 let cap: usize = w
276 .slots
277 .iter()
278 .map(|&s| capacities.get(s).copied().unwrap_or(0))
279 .sum();
280 if w.items.len() <= cap {
281 return false;
282 }
283 let slot_set: std::collections::HashSet<usize> = w.slots.iter().copied().collect();
284 w.items
285 .iter()
286 .all(|&i| i < adj.len() && adj[i].iter().all(|s| slot_set.contains(s)))
287}
288
289#[cfg(test)]
290#[path = "../../logicaffeine_tests/unit/logicaffeine_proof/matching/tests.rs"]
291mod tests;