eo-mcf 0.1.0

Exact minimum-cost-flow solver (cost-scaling push-relabel) with independent optimality certification.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Independent negative-cycle detection.
//!
//! A flow is optimal exactly when its residual graph has no negative-cost
//! cycle. This module decides that by computing the **exact minimum cycle
//! mean** μ of the residual graph with Howard's policy iteration
//! [cite: DASDAN-GUPTA-HILL §2.6]: a negative cycle exists iff μ < 0, which is
//! immediate from `μ = min_C w(C)/|C|` with `|C| > 0`
//! [cite: DASDAN-GUPTA-HILL §1.1].
//!
//! Policy iteration itself — value determination alternating with policy
//! improvement — is Howard's [cite: HOWARD-1960 §]. That book is about Markov
//! decision processes and computes the *gain* of a policy; it does not discuss
//! digraph cycle means, and the identification of that gain with the minimum
//! cycle mean is the later specialisation cited above. The `§` is left empty
//! because the book's chapter numbering has not been checked.
//!
//! ⚠ The cited implementation carries a floating-point precision parameter δ
//! and is described there as exact "but they may have precision problems".
//! This module has no δ: means are exact `i128` rationals (see below). That is
//! a deliberate divergence, not an omission to be repaired.
//!
//! # Why policy iteration and not another relaxation
//!
//! This is the second of two optimality proofs, and its value comes entirely
//! from being unlike the first. [`super::dual`] relaxes shortest-path
//! distances and checks arcs against them; a defect in that relaxation could
//! in principle produce a π that the arc check then blesses. Howard's shares
//! nothing with it — different algorithm, different state (a *policy*: one
//! chosen out-arc per node), different data structure, different failure
//! modes. When the two agree, they agree for independent reasons.
//! [`super::certify`] treats disagreement as a defect in one of them rather
//! than picking a winner.
//!
//! # Exactness
//!
//! μ is a rational `S/L` — the cost of some cycle over its length — and the
//! sign of a rational near zero is exactly what a float would get wrong. So
//! nothing here is floating point. Means are carried as normalised
//! `(numerator, denominator)` pairs in `i128`, compared by cross
//! multiplication, and the node biases are carried as numerators over the
//! current mean's denominator so they stay integral too.
//!
//! # Structure
//!
//! 1. Build the residual graph, with reverse adjacency.
//! 2. Drop every node that cannot keep walking forever — repeatedly remove
//!    nodes of out-degree zero. No node on a cycle is ever removed, and what
//!    remains has an out-arc at every node, which is what a policy needs.
//! 3. Iterate: evaluate the current policy (find its cycles, get each node's
//!    mean and bias), then improve it arc by arc, until nothing improves.

use crate::arith::{Cost, Flow, add_i128, gcd, mul_i128, neg};
use crate::error::VerifyError;
use crate::problem::Problem;

/// The residual graph's exact minimum cycle mean.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CycleCertificate {
    /// `(numerator, denominator)` of the minimum cycle mean, denominator
    /// positive and the pair in lowest terms; `None` when the residual graph
    /// has no cycle at all. Non-negative whenever the flow is optimal.
    pub minimum_mean: Option<(i128, i128)>,
}

/// Certify that the residual graph of `flows` has no negative cycle.
///
/// Does **not** check feasibility — that is
/// [`certify_feasibility`](super::certify_feasibility).
///
/// # Errors
///
/// [`VerifyError::NegativeCycle`] with the offending mean and a node on the
/// cycle; [`VerifyError::LengthMismatch`] for a mis-sized flow vector;
/// [`VerifyError::CycleSearchDidNotConverge`] if policy iteration exceeds its
/// safety bound.
pub fn certify_no_negative_cycle(
    problem: &Problem,
    flows: &[Flow],
) -> Result<CycleCertificate, VerifyError> {
    if flows.len() != problem.arc_count() {
        return Err(VerifyError::LengthMismatch {
            expected: problem.arc_count(),
            found: flows.len(),
        });
    }

    let graph = ResidualGraph::build(problem, flows)?;
    let Some(mut search) = PolicyIteration::new(&graph) else {
        // Nothing can cycle: the residual graph is acyclic.
        return Ok(CycleCertificate { minimum_mean: None });
    };
    search.run(&graph)?;

    let Some((numerator, denominator, node)) = search.minimum(&graph)? else {
        return Ok(CycleCertificate { minimum_mean: None });
    };
    if numerator < 0 {
        return Err(VerifyError::NegativeCycle {
            numerator,
            denominator,
            node: search.cycle_node_from(&graph, node),
        });
    }
    Ok(CycleCertificate {
        minimum_mean: Some((numerator, denominator)),
    })
}

/// Residual graph in CSR form, with reverse adjacency for the pruning pass.
struct ResidualGraph {
    node_count: usize,
    first_out: Vec<u32>,
    head: Vec<u32>,
    cost: Vec<Cost>,
    first_in: Vec<u32>,
    in_tail: Vec<u32>,
}

impl ResidualGraph {
    fn build(problem: &Problem, flows: &[Flow]) -> Result<Self, VerifyError> {
        let node_count = problem.node_count();
        let mut arcs: Vec<(u32, u32, Cost)> = Vec::with_capacity(problem.arc_count());
        for (arc, &flow) in problem.arcs().iter().zip(flows) {
            if flow < arc.upper {
                arcs.push((arc.tail as u32, arc.head as u32, arc.cost));
            }
            if flow > arc.lower {
                arcs.push((
                    arc.head as u32,
                    arc.tail as u32,
                    neg(arc.cost, "reverse residual arc cost")?,
                ));
            }
        }

        let mut first_out = vec![0u32; node_count + 1];
        let mut first_in = vec![0u32; node_count + 1];
        for &(u, v, _) in &arcs {
            first_out[u as usize + 1] += 1;
            first_in[v as usize + 1] += 1;
        }
        for i in 0..node_count {
            first_out[i + 1] += first_out[i];
            first_in[i + 1] += first_in[i];
        }

        let mut head = vec![0u32; arcs.len()];
        let mut cost = vec![0 as Cost; arcs.len()];
        let mut in_tail = vec![0u32; arcs.len()];
        let mut out_cursor: Vec<u32> = first_out[..node_count].to_vec();
        let mut in_cursor: Vec<u32> = first_in[..node_count].to_vec();
        for &(u, v, c) in &arcs {
            let slot = out_cursor[u as usize] as usize;
            out_cursor[u as usize] += 1;
            head[slot] = v;
            cost[slot] = c;

            let in_slot = in_cursor[v as usize] as usize;
            in_cursor[v as usize] += 1;
            in_tail[in_slot] = u;
        }

        Ok(Self {
            node_count,
            first_out,
            head,
            cost,
            first_in,
            in_tail,
        })
    }

    #[inline]
    fn out_arcs(&self, node: usize) -> std::ops::Range<usize> {
        self.first_out[node] as usize..self.first_out[node + 1] as usize
    }

    #[inline]
    fn in_arcs(&self, node: usize) -> std::ops::Range<usize> {
        self.first_in[node] as usize..self.first_in[node + 1] as usize
    }

    /// Nodes that can walk forever, i.e. that can reach a cycle. Obtained by
    /// repeatedly deleting nodes with no surviving out-arc.
    fn nodes_on_or_before_a_cycle(&self) -> Vec<bool> {
        let mut alive = vec![true; self.node_count];
        let mut out_degree: Vec<u32> = (0..self.node_count)
            .map(|v| self.first_out[v + 1] - self.first_out[v])
            .collect();
        let mut dead: Vec<usize> = (0..self.node_count)
            .filter(|&v| out_degree[v] == 0)
            .collect();

        while let Some(v) = dead.pop() {
            if !alive[v] {
                continue;
            }
            alive[v] = false;
            for a in self.in_arcs(v) {
                let u = self.in_tail[a] as usize;
                if alive[u] {
                    out_degree[u] -= 1;
                    if out_degree[u] == 0 {
                        dead.push(u);
                    }
                }
            }
        }
        alive
    }
}

/// Howard's policy iteration state.
struct PolicyIteration {
    alive: Vec<bool>,
    /// Chosen out-arc index per alive node.
    policy: Vec<u32>,
    /// Cycle mean per node, as a normalised rational.
    mean_num: Vec<i128>,
    mean_den: Vec<i128>,
    /// Node bias, as a numerator over `mean_den[node]`.
    bias: Vec<i128>,
    state: Vec<u8>,
    position: Vec<usize>,
}

impl PolicyIteration {
    /// Returns `None` when no node survives pruning — the graph is acyclic.
    fn new(graph: &ResidualGraph) -> Option<Self> {
        let alive = graph.nodes_on_or_before_a_cycle();
        if !alive.iter().any(|&a| a) {
            return None;
        }
        let node_count = graph.node_count;
        let mut policy = vec![u32::MAX; node_count];
        for v in 0..node_count {
            if !alive[v] {
                continue;
            }
            // Start from the cheapest surviving arc: a better initial policy
            // costs one pass and saves iterations.
            let mut best: Option<(Cost, u32)> = None;
            for a in graph.out_arcs(v) {
                if !alive[graph.head[a] as usize] {
                    continue;
                }
                let candidate = (graph.cost[a], a as u32);
                best = Some(best.map_or(candidate, |b| b.min(candidate)));
            }
            policy[v] = best.map_or(u32::MAX, |(_, a)| a);
        }

        Some(Self {
            alive,
            policy,
            mean_num: vec![0; node_count],
            mean_den: vec![1; node_count],
            bias: vec![0; node_count],
            state: vec![0; node_count],
            position: vec![0; node_count],
        })
    }

    fn run(&mut self, graph: &ResidualGraph) -> Result<(), VerifyError> {
        // Safety bound. Howard's converges in a few passes in practice; this
        // exists so a certifier can never spin, and firing it is reported
        // rather than swallowed.
        let limit = (graph.node_count as u64)
            .saturating_mul(4)
            .saturating_add(1024);
        for iteration in 0..limit {
            self.evaluate(graph)?;
            if !self.improve(graph)? {
                return Ok(());
            }
            let _ = iteration;
        }
        Err(VerifyError::CycleSearchDidNotConverge { iterations: limit })
    }

    /// Value determination: for the current policy, give every node the mean
    /// of the cycle it reaches and its bias relative to that cycle.
    fn evaluate(&mut self, graph: &ResidualGraph) -> Result<(), VerifyError> {
        self.state.iter_mut().for_each(|s| *s = 0);
        let mut walk: Vec<usize> = Vec::new();

        for start in 0..graph.node_count {
            if !self.alive[start] || self.state[start] != 0 {
                continue;
            }
            walk.clear();
            let mut node = start;
            while self.state[node] == 0 {
                self.state[node] = 1;
                self.position[node] = walk.len();
                walk.push(node);
                node = graph.head[self.policy[node] as usize] as usize;
            }

            // `tree_end` is where the pure tree part of this walk ends: the
            // whole walk when it ran into already-evaluated nodes, or the
            // cycle's entry point when it closed a cycle.
            let mut tree_end = walk.len();
            if self.state[node] == 1 {
                let entry = self.position[node];
                let length = walk.len() - entry;
                let mut sum: i128 = 0;
                for &member in &walk[entry..] {
                    let arc = self.policy[member] as usize;
                    sum = add_i128(sum, i128::from(graph.cost[arc]), "cycle cost")?;
                }
                let (num, den) = normalise(sum, length as i128);
                for &member in &walk[entry..] {
                    self.mean_num[member] = num;
                    self.mean_den[member] = den;
                }

                // The bias is pinned to zero at one node of the cycle, and
                // *which* node must be a property of the cycle rather than of
                // the traversal that happened to find it. Otherwise two nodes
                // on equal-mean cycles carry biases measured from different
                // origins, improvement compares quantities that are not
                // comparable, and the policy oscillates instead of converging
                // — the degenerate case that dominates here, because every arc
                // carrying flow strictly between its bounds contributes a
                // zero-mean two-cycle. Pinning the lowest node id makes the
                // choice canonical: a cycle that survives an iteration keeps
                // the same origin.
                //
                // "Select the lowest numbered node u ∈ C" is the rule as
                // published [cite: DASDAN-GUPTA-HILL §2.6 Fig. 10] — and the
                // contrast with Fig. 9 of the same paper, which says "select an
                // arbitrary node u ∈ C", is the point: Fig. 10 is the version
                // that comes with a termination proof.
                //
                // The underlying max-plus treatment reaches termination in the
                // degenerate case by a different route — keep the previous
                // policy arc when tied, and carry the previous bias forward at
                // the distinguished node — and explicitly chooses that node
                // *arbitrarily* [cite: COCHET-TERRASSON §4]. It is cited here
                // for why a conservative, canonical tie-break is needed at all,
                // not for this rule. Note it is max-plus (maximum circuit mean)
                // to this module's minimum cycle mean.
                let mut base = 0usize;
                for (offset, &member) in walk[entry..].iter().enumerate() {
                    if member < walk[entry + base] {
                        base = offset;
                    }
                }
                self.bias[walk[entry + base]] = 0;
                // Unwind backwards from the base, all the way round.
                for step in 1..length {
                    let offset = (base + length - step) % length;
                    let member = walk[entry + offset];
                    let successor = walk[entry + (offset + 1) % length];
                    self.bias[member] = self.step_bias(graph, member, successor, num, den)?;
                }
                tree_end = entry;
            }

            for i in (0..tree_end).rev() {
                let member = walk[i];
                let successor = if i + 1 < walk.len() {
                    walk[i + 1]
                } else {
                    node
                };
                let (num, den) = (self.mean_num[successor], self.mean_den[successor]);
                self.mean_num[member] = num;
                self.mean_den[member] = den;
                self.bias[member] = self.step_bias(graph, member, successor, num, den)?;
            }

            for &member in &walk {
                self.state[member] = 2;
            }
        }
        Ok(())
    }

    /// `h(v) = c(v, σ(v)) + h(σ(v)) − λ`, carried as a numerator over `den`.
    fn step_bias(
        &self,
        graph: &ResidualGraph,
        node: usize,
        successor: usize,
        num: i128,
        den: i128,
    ) -> Result<i128, VerifyError> {
        let arc = self.policy[node] as usize;
        let scaled = mul_i128(i128::from(graph.cost[arc]), den, "bias arc term")?;
        let with_successor = add_i128(scaled, self.bias[successor], "bias accumulation")?;
        Ok(add_i128(with_successor, -num, "bias accumulation")?)
    }

    /// Policy improvement: give every node its best out-arc, ranked by the
    /// mean it leads to and then by bias. Returns whether anything changed.
    fn improve(&mut self, graph: &ResidualGraph) -> Result<bool, VerifyError> {
        let mut improved = false;
        for v in 0..graph.node_count {
            if !self.alive[v] {
                continue;
            }
            let mut best_arc = self.policy[v];
            let (mut best_num, mut best_den) = (self.mean_num[v], self.mean_den[v]);
            let mut best_bias = self.bias[v];

            for a in graph.out_arcs(v) {
                let w = graph.head[a] as usize;
                if !self.alive[w] {
                    continue;
                }
                let (num, den) = (self.mean_num[w], self.mean_den[w]);
                match compare_rationals((num, den), (best_num, best_den))? {
                    std::cmp::Ordering::Less => {
                        best_arc = a as u32;
                        best_num = num;
                        best_den = den;
                        best_bias = bias_of(graph, a, self.bias[w], num, den)?;
                    }
                    std::cmp::Ordering::Equal => {
                        let candidate = bias_of(graph, a, self.bias[w], num, den)?;
                        if candidate < best_bias {
                            best_arc = a as u32;
                            best_bias = candidate;
                        }
                    }
                    std::cmp::Ordering::Greater => {}
                }
            }

            if best_arc != self.policy[v] {
                self.policy[v] = best_arc;
                improved = true;
            }
        }
        Ok(improved)
    }

    /// The smallest cycle mean over all surviving nodes, with a witness node.
    ///
    /// The comparison goes through [`compare_rationals`] rather than
    /// multiplying inline. "This cannot overflow in practice" is not a claim a
    /// certifier gets to make about its own arithmetic — an unchecked `i128`
    /// product is a panic in a debug build, and this crate does not panic in
    /// product code.
    fn minimum(&self, graph: &ResidualGraph) -> Result<Option<(i128, i128, usize)>, VerifyError> {
        let mut best: Option<(i128, i128, usize)> = None;
        for v in 0..graph.node_count {
            if !self.alive[v] {
                continue;
            }
            let candidate = (self.mean_num[v], self.mean_den[v], v);
            best = Some(match best {
                None => candidate,
                Some(current) => {
                    // Ties keep the lower node id, which is reached first.
                    match compare_rationals((candidate.0, candidate.1), (current.0, current.1))? {
                        std::cmp::Ordering::Less => candidate,
                        _ => current,
                    }
                }
            });
        }
        Ok(best)
    }

    /// Follow the final policy from `node` until it repeats — that lands on
    /// the cycle whose mean `node` was assigned.
    fn cycle_node_from(&self, graph: &ResidualGraph, node: usize) -> usize {
        let mut seen = vec![false; graph.node_count];
        let mut current = node;
        for _ in 0..=graph.node_count {
            if seen[current] {
                return current;
            }
            seen[current] = true;
            let arc = self.policy[current] as usize;
            if arc >= graph.head.len() {
                return current;
            }
            current = graph.head[arc] as usize;
        }
        current
    }
}

/// `c(v,w)·den + h(w) − num`, the bias node `v` would have if it chose `a`.
fn bias_of(
    graph: &ResidualGraph,
    arc: usize,
    successor_bias: i128,
    num: i128,
    den: i128,
) -> Result<i128, VerifyError> {
    let scaled = mul_i128(i128::from(graph.cost[arc]), den, "candidate bias term")?;
    let with_successor = add_i128(scaled, successor_bias, "candidate bias")?;
    Ok(add_i128(with_successor, -num, "candidate bias")?)
}

/// Reduce `sum/length` to lowest terms with a positive denominator.
fn normalise(sum: i128, length: i128) -> (i128, i128) {
    if length == 0 {
        return (0, 1);
    }
    let divisor = gcd(sum.unsigned_abs(), length.unsigned_abs()).max(1) as i128;
    (sum / divisor, length / divisor)
}

/// Compare two rationals with positive denominators, exactly.
fn compare_rationals(a: (i128, i128), b: (i128, i128)) -> Result<std::cmp::Ordering, VerifyError> {
    let left = mul_i128(a.0, b.1, "cycle mean comparison")?;
    let right = mul_i128(b.0, a.1, "cycle mean comparison")?;
    Ok(left.cmp(&right))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn acyclic_residual_graph_has_no_cycle_mean() {
        // A saturated single arc: the only residual arc is the reverse one.
        let problem = Problem::builder(2)
            .supply(0, 1)
            .supply(1, -1)
            .edge(0, 1, 1, 5)
            .build()
            .unwrap();
        let certificate = certify_no_negative_cycle(&problem, &[1]).unwrap();
        assert_eq!(certificate.minimum_mean, None);
    }

    #[test]
    fn finds_the_exact_mean_of_a_positive_cycle() {
        // 0→1 cost 1, 1→0 cost 2: the only residual cycle has mean 3/2.
        let problem = Problem::builder(2)
            .edge(0, 1, 4, 1)
            .edge(1, 0, 4, 2)
            .build()
            .unwrap();
        let certificate = certify_no_negative_cycle(&problem, &[0, 0]).unwrap();
        assert_eq!(certificate.minimum_mean, Some((3, 2)));
    }

    #[test]
    fn detects_a_negative_cycle_and_names_a_node_on_it() {
        let problem = Problem::builder(3)
            .edge(0, 1, 4, -5)
            .edge(1, 2, 4, 1)
            .edge(2, 0, 4, 1)
            .build()
            .unwrap();
        let err = certify_no_negative_cycle(&problem, &[0, 0, 0]).unwrap_err();
        match err {
            VerifyError::NegativeCycle {
                numerator,
                denominator,
                node,
            } => {
                assert_eq!((numerator, denominator), (-1, 1), "mean of (−5+1+1)/3");
                assert!(node < 3);
            }
            other => panic!("expected NegativeCycle, got {other:?}"),
        }
    }

    #[test]
    fn negative_self_loop_is_a_length_one_cycle() {
        let problem = Problem::builder(1).arc(0, 0, 0, 3, -7).build().unwrap();
        let err = certify_no_negative_cycle(&problem, &[0]).unwrap_err();
        assert!(matches!(
            err,
            VerifyError::NegativeCycle {
                numerator: -7,
                denominator: 1,
                node: 0
            }
        ));
        // Saturated, the forward residual arc is gone and the reverse costs +7.
        assert_eq!(
            certify_no_negative_cycle(&problem, &[3])
                .unwrap()
                .minimum_mean,
            Some((7, 1))
        );
    }

    #[test]
    fn picks_the_minimum_among_several_cycles() {
        // Two disjoint cycles: means 5/1 and 1/2. The minimum is 1/2.
        let problem = Problem::builder(4)
            .edge(0, 1, 1, 5)
            .edge(1, 0, 1, 5)
            .edge(2, 3, 1, 0)
            .edge(3, 2, 1, 1)
            .build()
            .unwrap();
        let certificate = certify_no_negative_cycle(&problem, &[0, 0, 0, 0]).unwrap();
        assert_eq!(certificate.minimum_mean, Some((1, 2)));
    }

    #[test]
    fn agrees_with_brute_force_on_small_random_graphs() {
        // Exhaustive minimum-mean-cycle over every simple cycle, compared
        // against Howard's on the same residual graphs. A verifier is only
        // worth having if something independent says it is right.
        let mut seed = 0x5eed_1234_u64;
        let mut next = move || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed
        };

        for _ in 0..300 {
            let n = 2 + (next() % 5) as usize;
            let arc_count = 1 + (next() % 10) as usize;
            let mut builder = Problem::builder(n);
            let mut arcs = Vec::new();
            for _ in 0..arc_count {
                let u = (next() % n as u64) as usize;
                let v = (next() % n as u64) as usize;
                let cost = (next() % 21) as i64 - 10;
                arcs.push((u, v, cost));
                builder = builder.edge(u, v, 3, cost);
            }
            let Ok(problem) = builder.build() else {
                continue;
            };
            let flows = vec![0; arc_count];

            // Residual arcs at zero flow: forward only (lower bound is 0).
            let expected = brute_force_minimum_mean(n, &arcs);
            let actual = match certify_no_negative_cycle(&problem, &flows) {
                Ok(c) => c.minimum_mean,
                Err(VerifyError::NegativeCycle {
                    numerator,
                    denominator,
                    ..
                }) => Some((numerator, denominator)),
                Err(other) => panic!("unexpected verifier failure: {other:?}"),
            };
            assert_eq!(actual, expected, "graph {arcs:?}");
        }
    }

    /// Minimum mean over all simple cycles, by exhaustive depth-first search.
    fn brute_force_minimum_mean(n: usize, arcs: &[(usize, usize, i64)]) -> Option<(i128, i128)> {
        let mut best: Option<(i128, i128)> = None;
        // Every simple cycle is enumerated once, as the path leaving its
        // lowest-numbered node and returning to it.
        for start in 0..n {
            let mut path: Vec<usize> = vec![start];
            let mut on_path = vec![false; n];
            on_path[start] = true;
            walk(start, start, 0, arcs, &mut path, &mut on_path, &mut best);
        }
        best
    }

    fn walk(
        start: usize,
        node: usize,
        cost: i128,
        arcs: &[(usize, usize, i64)],
        path: &mut Vec<usize>,
        on_path: &mut Vec<bool>,
        best: &mut Option<(i128, i128)>,
    ) {
        for &(u, v, w) in arcs {
            if u != node {
                continue;
            }
            let total = cost + i128::from(w);
            if v == start {
                let (num, den) = normalise(total, path.len() as i128);
                let better = match *best {
                    None => true,
                    Some((bn, bd)) => num * bd < bn * den,
                };
                if better {
                    *best = Some((num, den));
                }
            } else if v > start && !on_path[v] {
                on_path[v] = true;
                path.push(v);
                walk(start, v, total, arcs, path, on_path, best);
                path.pop();
                on_path[v] = false;
            }
        }
    }
}