Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-graph/src/flow.rs

//! Maximum flow from one source to one target: push-relabel rounds on the CPU device's
//! workers, then Dinic's phases to finish.
//!
//! Each entry `u -> v` of the capacity matrix is an arc of its capacity (a matrix with no
//! values: capacity 1 each, so the flow counts edge-disjoint paths); parallel entries are
//! arcs of their own, self-loops and zero capacities carry nothing. The residual graph
//! keeps every arc beside its reverse (capacity 0) in the tail's list; the entries into
//! each vertex come from the device's transpose of the entry numbers, so one pass over the
//! rows on the workers writes every vertex's arcs in order; the push-relabel rounds see the
//! capacities left as atomics.
//!
//! Push-relabel (Goldberg and Tarjan, in Hong's lock-free form): the source's arcs are
//! filled, then in rounds every vertex with excess is discharged on the workers: it pushes
//! its excess down to its lowest neighbours through the arcs with capacity left (an atomic
//! take from the arc, an atomic add to its reverse and to the neighbour's excess), and
//! lifts itself one above its lowest neighbour when none is lower. A vertex that gets
//! excess is queued for the next round once (a stamp per vertex). Between rounds, after
//! about one pass of work over the arcs, the heights are set again to the exact distances
//! to the target over the residual arcs (a breadth-first search back from the target, each
//! frontier on the workers), and the vertices that no longer reach the target to `n` plus
//! their distance back to the source, so their excess returns. The rounds end with no
//! excess left anywhere but at the ends: a flow.
//!
//! Dinic's phases then run on that flow (a level search from the source on the workers, a
//! blocking flow on one thread): normally one search that does not reach the target, which
//! proves the flow maximum and names the source's side of a minimum cut. Should the rounds
//! not settle (a bound on heights and rounds), the residual graph is built again and the
//! phases alone find the flow; the same when the capacities out of the source do not sum
//! within `u64` (an excess must fit). The value is the same whatever the workers; the flow
//! on each arc may differ between thread counts.

use std::sync::atomic::Ordering::Relaxed;
use std::sync::atomic::{AtomicU32, AtomicU64};

use arrow_buffer::ScalarBuffer;
use kleene_sparse::{
    CpuBackend, CpuDevice, Csr, Pattern, SparseBackend, Value, atomic_u32s, atomic_words,
};

use crate::GraphError;
use crate::centrality::{PIECE, each_piece, pieces_by_entries};

/// A maximum flow: its value, the flow on every entry, the source's side of a minimum cut.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MaxFlow {
    /// The flow from the source to the target.
    pub value: u128,
    /// The flow on each entry of the capacity matrix, in the order of its entries.
    pub flow: Vec<u64>,
    /// The vertices the source still reaches through capacity left: the source's side of a
    /// minimum cut (its arcs out are full, its arcs in carry nothing).
    pub source_side: Vec<bool>,
    /// Dinic's phases run after the push-relabel rounds (level searches that reached the
    /// target).
    pub phases: u32,
    /// Push-relabel rounds run (each the active vertices discharged on the workers).
    pub rounds: u32,
}

/// No level.
const FAR: u32 = u32::MAX;

/// Vertices of a frontier per piece of a level search.
const FRONT: usize = 1 << 10;

/// Active vertices per piece of a push-relabel round.
const ACTIVE: usize = 1 << 8;

/// How capacities are counted: words of `u64`, whole numbers ([`Whole`]) or the bits of
/// non-negative floats ([`Real`]). The residual graph, the excesses and the flow keep words.
trait Units: Copy + Send + Sync {
    /// Whether `x` holds anything (a float: more than the tolerance).
    fn some(self, x: u64) -> bool;
    fn add(self, a: u64, b: u64) -> u64;
    /// `a - b` (a float: never below 0).
    fn sub(self, a: u64, b: u64) -> u64;
    fn min(self, a: u64, b: u64) -> u64;
    /// Take `d` from `x` (atomically): what is left.
    fn take(self, x: &AtomicU64, d: u64) -> u64;
    /// Give `d` to `x` (atomically): what it held before.
    fn give(self, x: &AtomicU64, d: u64) -> u64;
}

/// Whole capacities: words as they are.
#[derive(Clone, Copy)]
struct Whole;

impl Units for Whole {
    fn some(self, x: u64) -> bool {
        x > 0
    }
    fn add(self, a: u64, b: u64) -> u64 {
        a + b
    }
    fn sub(self, a: u64, b: u64) -> u64 {
        a - b
    }
    fn min(self, a: u64, b: u64) -> u64 {
        a.min(b)
    }
    fn take(self, x: &AtomicU64, d: u64) -> u64 {
        x.fetch_sub(d, Relaxed) - d
    }
    fn give(self, x: &AtomicU64, d: u64) -> u64 {
        x.fetch_add(d, Relaxed)
    }
}

/// Float capacities: the bits of non-negative floats; at most `tol` counts as nothing.
#[derive(Clone, Copy)]
struct Real {
    tol: f64,
}

impl Real {
    /// `f` applied to the float in `x`, by compare-and-swap: the float it held before.
    fn update(x: &AtomicU64, f: impl Fn(f64) -> f64) -> f64 {
        let mut old = x.load(Relaxed);
        loop {
            let new = f(f64::from_bits(old)).to_bits();
            match x.compare_exchange_weak(old, new, Relaxed, Relaxed) {
                Ok(_) => return f64::from_bits(old),
                Err(now) => old = now,
            }
        }
    }
}

impl Units for Real {
    fn some(self, x: u64) -> bool {
        f64::from_bits(x) > self.tol
    }
    fn add(self, a: u64, b: u64) -> u64 {
        (f64::from_bits(a) + f64::from_bits(b)).to_bits()
    }
    fn sub(self, a: u64, b: u64) -> u64 {
        (f64::from_bits(a) - f64::from_bits(b)).max(0.0).to_bits()
    }
    fn min(self, a: u64, b: u64) -> u64 {
        f64::from_bits(a).min(f64::from_bits(b)).to_bits()
    }
    fn take(self, x: &AtomicU64, d: u64) -> u64 {
        let d = f64::from_bits(d);
        (Real::update(x, |v| (v - d).max(0.0)) - d)
            .max(0.0)
            .to_bits()
    }
    fn give(self, x: &AtomicU64, d: u64) -> u64 {
        let d = f64::from_bits(d);
        Real::update(x, |v| v + d).to_bits()
    }
}

/// The residual graph: arcs grouped by tail, each vertex's forward arcs (one per entry of
/// its row, in the row's order) before its reverse ones (one per entry into it, in the order
/// of the transpose's row). Entry `e` of row `u` is the forward arc `e + toff[u]`, so arc `a`
/// of `u` sits at `start[u] = off[u] + toff[u]` plus its place. A self-loop or an entry of
/// no capacity is an arc too, with nothing left.
struct Residual {
    start: Vec<usize>,
    head: Vec<u32>,
    left: Vec<u64>,
    mate: Vec<u64>,
}

impl Residual {
    /// The arcs of `pat` with the capacities `cap(e)` of its entries. The entries into each
    /// vertex come from the transpose of the entry numbers (the device's bucket sort, on the
    /// workers; the numbers `u32` while they fit); then one pass on the workers writes each
    /// vertex's arcs in place, in order, each reverse arc setting its forward arc's mate (the
    /// one write out of order).
    fn build(pat: &Pattern, cap: &(impl Fn(usize) -> u64 + Sync), cpu: &CpuDevice) -> Residual {
        let nnz = pat.indices().len();
        let pieces = nnz.div_ceil(1 << 16);
        let each = |p: usize| (p << 16)..((p + 1) << 16).min(nnz);
        if u32::try_from(nnz).is_ok() {
            let mut number = vec![0u32; nnz];
            let w = atomic_u32s(&mut number);
            each_piece(cpu, pieces, |p| {
                for e in each(p) {
                    w[e].store(e as u32, Relaxed);
                }
            });
            Residual::fill(pat, cap, number, cpu)
        } else {
            let mut number = vec![0u64; nnz];
            let w = atomic_words(&mut number);
            each_piece(cpu, pieces, |p| {
                for e in each(p) {
                    w[e].store(e as u64, Relaxed);
                }
            });
            Residual::fill(pat, cap, number, cpu)
        }
    }

    /// [`Residual::build`] with the entry numbers `number` (`number[e] = e`).
    fn fill<T: Value + Copy + Into<u64>>(
        pat: &Pattern,
        cap: &(impl Fn(usize) -> u64 + Sync),
        number: Vec<T>,
        cpu: &CpuDevice,
    ) -> Residual {
        let (off, idx) = (pat.offsets(), pat.indices());
        let n = off.len() - 1;
        let numbered = Csr::with_pattern(pat.clone(), Some(ScalarBuffer::from(number)))
            .expect("one number per entry");
        let tr = <CpuBackend as SparseBackend>::transpose(&numbered, cpu);
        drop(numbered);
        let (toff, tidx) = (tr.pattern().offsets(), tr.pattern().indices());
        let tent = tr.values().expect("the transpose keeps the numbers");
        let ends: Vec<u64> = (0..=n).map(|u| off[u] + toff[u]).collect();
        let arcs = ends[n] as usize;
        let (mut head, mut left, mut mate) = (vec![0u32; arcs], vec![0u64; arcs], vec![0u64; arcs]);
        let cuts = pieces_by_entries(&ends, PIECE);
        {
            let (h, l, m) = (
                atomic_u32s(&mut head),
                atomic_words(&mut left),
                atomic_words(&mut mate),
            );
            let ends = &ends;
            each_piece(cpu, cuts.len() - 1, |p| {
                for u in cuts[p]..cuts[p + 1] {
                    let mut a = ends[u] as usize;
                    for e in off[u] as usize..off[u + 1] as usize {
                        let v = idx[e];
                        h[a].store(v, Relaxed);
                        if v as usize != u {
                            l[a].store(cap(e), Relaxed);
                        }
                        a += 1;
                    }
                    // the reverse arcs: entry `e` of row `w` into `u`
                    for k in toff[u] as usize..toff[u + 1] as usize {
                        let w = tidx[k] as usize;
                        let f = (tent[k].into() + toff[w]) as usize;
                        h[a].store(w as u32, Relaxed);
                        m[a].store(f as u64, Relaxed);
                        m[f].store(a as u64, Relaxed);
                        a += 1;
                    }
                }
            });
        }
        Residual {
            start: ends.iter().map(|&x| x as usize).collect(),
            head,
            left,
            mate,
        }
    }
}

/// The state of the push-relabel rounds beside the residual graph.
struct Preflow<'r, U> {
    units: U,
    start: &'r [usize],
    head: &'r [u32],
    mate: &'r [u64],
    left: &'r [AtomicU64],
    height: &'r [AtomicU32],
    excess: &'r [AtomicU64],
    /// The round a vertex was last queued for.
    stamp: &'r [AtomicU32],
    s: usize,
    t: usize,
    /// No vertex of a flow in progress climbs this high (`2n`).
    top: u32,
}

/// What a piece of a round gives: the vertices it queued, the arcs it scanned, and whether
/// a vertex climbed past the bound.
struct Discharged {
    next: Vec<u32>,
    work: u64,
    stuck: bool,
}

impl<U: Units> Preflow<'_, U> {
    /// Queue `v` (it just got excess) for round `round`, once.
    fn queue(&self, v: usize, round: u32, out: &mut Discharged) {
        if v != self.s && v != self.t && self.stamp[v].swap(round, Relaxed) != round {
            out.next.push(v as u32);
        }
    }

    /// Discharge `u` in this round: push its excess to its lowest neighbours, lifting it
    /// one above them when none is lower, until it has none (Hong's lock-free rule: each
    /// push goes to a neighbour that was lowest when read, heights only rise in a round).
    fn discharge(&self, u: usize, round: u32, out: &mut Discharged) {
        let arcs = self.start[u]..self.start[u + 1];
        let n = self.units;
        let mut e = self.excess[u].load(Relaxed);
        while n.some(e) {
            let hu = self.height[u].load(Relaxed);
            let mut low = u32::MAX;
            for a in arcs.clone() {
                if n.some(self.left[a].load(Relaxed)) {
                    low = low.min(self.height[self.head[a] as usize].load(Relaxed));
                }
            }
            out.work += arcs.len() as u64;
            if low == u32::MAX {
                // excess with no arc out: not a preflow any more
                out.stuck = true;
                return;
            }
            if hu <= low {
                if low + 1 >= self.top {
                    out.stuck = true;
                    return;
                }
                self.height[u].store(low + 1, Relaxed);
                continue;
            }
            for a in arcs.clone() {
                let c = self.left[a].load(Relaxed);
                let v = self.head[a] as usize;
                if !n.some(c) || self.height[v].load(Relaxed) != low {
                    continue;
                }
                // only `u` takes from its arcs: `c` is at most what is left
                let d = n.min(c, e);
                n.take(&self.left[a], d);
                n.give(&self.left[self.mate[a] as usize], d);
                e = n.take(&self.excess[u], d);
                if !n.some(n.give(&self.excess[v], d)) {
                    self.queue(v, round, out);
                }
                if !n.some(e) {
                    break;
                }
            }
            out.work += arcs.len() as u64;
        }
    }

    /// Set every height to its exact distance to the target over the residual arcs; those
    /// that do not reach it to `n` plus their distance to the source; those that reach
    /// neither to the bound. Between rounds only (no push runs).
    fn relabel_all(&self, cpu: &CpuDevice, frontier: &mut Vec<u32>) {
        let n = self.height.len() as u32;
        each_piece(cpu, self.height.len().div_ceil(1 << 16), |p| {
            for h in &self.height[p << 16..((p + 1) << 16).min(self.height.len())] {
                h.store(FAR, Relaxed);
            }
        });
        self.height[self.t].store(0, Relaxed);
        self.height[self.s].store(n, Relaxed);
        for (from, base) in [(self.t, 0u32), (self.s, n)] {
            frontier.clear();
            frontier.push(from as u32);
            let mut d = base;
            while !frontier.is_empty() {
                d += 1;
                let next = self.back_step(frontier, d, cpu);
                frontier.clear();
                for x in next {
                    frontier.extend(x);
                }
            }
        }
        each_piece(cpu, self.height.len().div_ceil(1 << 16), |p| {
            for h in &self.height[p << 16..((p + 1) << 16).min(self.height.len())] {
                if h.load(Relaxed) == FAR {
                    h.store(self.top, Relaxed);
                }
            }
        });
    }

    /// One frontier of a search backwards over the residual arcs (`z` before `y` when the
    /// arc `z -> y` has capacity left): the vertices it claims get `d`.
    fn back_step(&self, front: &[u32], d: u32, cpu: &CpuDevice) -> Vec<Vec<u32>> {
        each_piece(cpu, front.len().div_ceil(FRONT), |p| {
            let mut mine = Vec::new();
            for &y in &front[p * FRONT..((p + 1) * FRONT).min(front.len())] {
                let y = y as usize;
                for a in self.start[y]..self.start[y + 1] {
                    let z = self.head[a] as usize;
                    if self
                        .units
                        .some(self.left[self.mate[a] as usize].load(Relaxed))
                        && self.height[z].load(Relaxed) == FAR
                        && self.height[z]
                            .compare_exchange(FAR, d, Relaxed, Relaxed)
                            .is_ok()
                    {
                        mine.push(z as u32);
                    }
                }
            }
            mine
        })
    }
}

/// The push-relabel rounds on `r` (see the module): `Some(rounds)` when they ended with a
/// flow, `None` when they gave up (a vertex past the bound, too many rounds; `r` is then
/// not a flow).
fn push_relabel<U: Units>(
    units: U,
    r: &mut Residual,
    s: usize,
    t: usize,
    cpu: &CpuDevice,
) -> Option<u32> {
    let n = r.start.len() - 1;
    let arcs = r.head.len() as u64;
    let (mut height, mut excess, mut stamp) = (vec![0u32; n], vec![0u64; n], vec![0u32; n]);
    let pf = Preflow {
        units,
        start: &r.start,
        head: &r.head,
        mate: &r.mate,
        left: atomic_words(&mut r.left),
        height: atomic_u32s(&mut height),
        excess: atomic_words(&mut excess),
        stamp: atomic_u32s(&mut stamp),
        s,
        t,
        top: 2 * n as u32,
    };
    // fill the source's arcs
    let mut active: Vec<u32> = Vec::new();
    for a in pf.start[s]..pf.start[s + 1] {
        let c = pf.left[a].load(Relaxed);
        if units.some(c) {
            pf.left[a].store(0, Relaxed);
            units.give(&pf.left[pf.mate[a] as usize], c);
            let v = pf.head[a] as usize;
            if !units.some(units.give(&pf.excess[v], c)) && v != t {
                pf.stamp[v].store(1, Relaxed);
                active.push(v as u32);
            }
        }
    }
    let mut frontier = Vec::new();
    // a pass of work over the arcs between exact heights
    let every = arcs + n as u64;
    let mut since = every;
    let mut round = 0u32;
    while !active.is_empty() {
        if since >= every {
            pf.relabel_all(cpu, &mut frontier);
            since = 0;
        }
        round += 1;
        if round as usize > 4 * n + 64 {
            return None;
        }
        let pf = &pf;
        let list = &active;
        let done = each_piece(cpu, list.len().div_ceil(ACTIVE), |p| {
            let mut out = Discharged {
                next: Vec::new(),
                work: 0,
                stuck: false,
            };
            for &u in &list[p * ACTIVE..((p + 1) * ACTIVE).min(list.len())] {
                pf.discharge(u as usize, round + 1, &mut out);
                if out.stuck {
                    break;
                }
            }
            out
        });
        active.clear();
        for d in done {
            if d.stuck {
                return None;
            }
            since += d.work;
            active.extend(d.next);
        }
    }
    Some(round)
}

/// The checks every maximum flow makes: a square matrix, the ends inside it and apart.
fn check_ends(n: usize, cols: usize, source: u32, target: u32) -> crate::Result<()> {
    if cols != n {
        return Err(GraphError::NotSquare { rows: n, cols });
    }
    for s in [source, target] {
        if s as usize >= n {
            return Err(GraphError::SourceOutOfRange {
                source: s,
                vertices: n,
            });
        }
    }
    if source == target {
        return Err(GraphError::Flow(format!(
            "source and target are the same vertex ({source})"
        )));
    }
    Ok(())
}

/// A flow found: the flow word on each entry, the words that leave the source on its
/// entries and that come back to it on its reverse arcs, the source's side of a cut, the
/// phases and rounds.
struct Found {
    flow: Vec<u64>,
    out: Vec<u64>,
    back: Vec<u64>,
    source_side: Vec<bool>,
    phases: u32,
    rounds: u32,
}

/// Push-relabel rounds (when `rounds` allows them), then Dinic's phases, on the capacity
/// words `cap` of the pattern `pat`.
fn solve<U: Units>(
    units: U,
    pat: &Pattern,
    cap: &(impl Fn(usize) -> u64 + Sync),
    s: usize,
    t: usize,
    rounds_allowed: bool,
    cpu: &CpuDevice,
) -> Found {
    let (off, idx) = (pat.offsets(), pat.indices());
    let n = off.len() - 1;
    let mut r = Residual::build(pat, cap, cpu);
    let mut rounds = 0;
    if rounds_allowed && 2 * (n as u64) < u64::from(FAR) {
        match push_relabel(units, &mut r, s, t, cpu) {
            Some(k) => rounds = k,
            None => r = Residual::build(pat, cap, cpu),
        }
    }
    let (source_side, phases) = dinic(units, &mut r, s, t, cpu);
    let mut flow = vec![0u64; idx.len()];
    let cuts = pieces_by_entries(off, PIECE);
    {
        let fl = atomic_words(&mut flow);
        let r = &r;
        each_piece(cpu, cuts.len() - 1, |p| {
            for u in cuts[p]..cuts[p + 1] {
                // entry `e` is the arc `e + (start[u] - off[u])`
                let at = r.start[u] - off[u] as usize;
                for e in off[u] as usize..off[u + 1] as usize {
                    if idx[e] as usize != u {
                        fl[e].store(units.sub(cap(e), r.left[e + at]), Relaxed);
                    }
                }
            }
        });
    }
    // the source's entries, then its reverse arcs (each holds the flow on its entry into
    // the source; a self-loop's holds nothing)
    let row = off[s] as usize..off[s + 1] as usize;
    let out: Vec<u64> = flow[row.clone()].to_vec();
    let back = r.left[r.start[s] + row.len()..r.start[s + 1]].to_vec();
    Found {
        flow,
        out,
        back,
        source_side,
        phases,
        rounds,
    }
}

/// A maximum flow from `source` to `target` over the capacities `capacities` (entry
/// `u -> v` an arc of its value; a matrix with no values: 1 each): push-relabel rounds on
/// the workers, then Dinic's phases (see the module). Refused: a matrix that is not square,
/// a source or target outside it, a source that is the target.
pub fn max_flow<W: Value + Copy + Into<u64>>(
    capacities: &Csr<W>,
    source: u32,
    target: u32,
    cpu: &CpuDevice,
) -> crate::Result<MaxFlow> {
    let n = capacities.nrows();
    check_ends(n, capacities.ncols(), source, target)?;
    let (off, idx) = (
        capacities.pattern().offsets(),
        capacities.pattern().indices(),
    );
    let vals = capacities.values();
    let cap = |e: usize| vals.map_or(1, |v| v[e].into());
    let s = source as usize;
    // an excess holds at most what leaves the source
    let leaving: u128 = (off[s] as usize..off[s + 1] as usize)
        .filter(|&e| idx[e] as usize != s)
        .map(|e| u128::from(cap(e)))
        .sum();
    let f = solve(
        Whole,
        capacities.pattern(),
        &cap,
        s,
        target as usize,
        leaving <= u128::from(u64::MAX),
        cpu,
    );
    let value = f.out.iter().map(|&x| u128::from(x)).sum::<u128>()
        - f.back.iter().map(|&x| u128::from(x)).sum::<u128>();
    Ok(MaxFlow {
        value,
        flow: f.flow,
        source_side: f.source_side,
        phases: f.phases,
        rounds: f.rounds,
    })
}

/// A maximum flow over float capacities: as [`MaxFlow`], the value and the flow on each
/// entry as floats.
#[derive(Clone, Debug, PartialEq)]
pub struct MaxFlowF64 {
    /// The flow from the source to the target.
    pub value: f64,
    /// The flow on each entry of the capacity matrix, in the order of its entries.
    pub flow: Vec<f64>,
    /// The source's side of a minimum cut.
    pub source_side: Vec<bool>,
    /// Dinic's phases run after the push-relabel rounds.
    pub phases: u32,
    /// Push-relabel rounds run.
    pub rounds: u32,
}

/// [`max_flow`] over float capacities, by the same rounds and phases on floats: an arc or
/// an excess of at most `largest capacity * vertices * f64::EPSILON` counts as empty, so
/// the flow is conserved and the cut full within that. Refused besides: a negative,
/// infinite or NaN capacity.
pub fn max_flow_f64(
    capacities: &Csr<f64>,
    source: u32,
    target: u32,
    cpu: &CpuDevice,
) -> crate::Result<MaxFlowF64> {
    let n = capacities.nrows();
    check_ends(n, capacities.ncols(), source, target)?;
    let vals = capacities.values();
    let mut largest = 0f64;
    for &c in vals.map_or(&[][..], |v| &v[..]) {
        if !(c >= 0.0 && c.is_finite()) {
            return Err(GraphError::Flow(format!(
                "a capacity of {c}: capacities are finite and not negative"
            )));
        }
        largest = largest.max(c);
    }
    if vals.is_none() {
        largest = 1.0;
    }
    let units = Real {
        tol: largest * n as f64 * f64::EPSILON,
    };
    // 0.0 for -0.0 and the empty: a word of 0 carries nothing
    let cap = |e: usize| {
        let c = vals.map_or(1.0, |v| v[e]);
        if c > 0.0 { c.to_bits() } else { 0 }
    };
    let f = solve(
        units,
        capacities.pattern(),
        &cap,
        source as usize,
        target as usize,
        true,
        cpu,
    );
    let sum = |w: &[u64]| w.iter().map(|&x| f64::from_bits(x)).sum::<f64>();
    Ok(MaxFlowF64 {
        value: (sum(&f.out) - sum(&f.back)).max(0.0),
        flow: f.flow.iter().map(|&x| f64::from_bits(x)).collect(),
        source_side: f.source_side,
        phases: f.phases,
        rounds: f.rounds,
    })
}

/// Dinic's phases on `r` from whatever flow it holds: the source's side of a minimum cut at
/// the end and the phases that reached the target.
fn dinic<U: Units>(
    units: U,
    r: &mut Residual,
    s: usize,
    t: usize,
    cpu: &CpuDevice,
) -> (Vec<bool>, u32) {
    let n = r.start.len() - 1;
    let mut lvl = vec![0u32; n];
    let mut lv = vec![FAR; n];
    let mut cur = vec![0usize; n];
    let mut path: Vec<usize> = Vec::new();
    let mut frontier: Vec<u32> = Vec::new();
    let mut phases = 0u32;
    loop {
        // 1. levels from the source, up to the target's
        {
            let level = atomic_u32s(&mut lvl);
            each_piece(cpu, n.div_ceil(1 << 16), |p| {
                for x in &level[p << 16..((p + 1) << 16).min(n)] {
                    x.store(FAR, Relaxed);
                }
            });
            level[s].store(0, Relaxed);
            frontier.clear();
            frontier.push(s as u32);
            let mut d = 0u32;
            let r = &*r;
            while !frontier.is_empty() && level[t].load(Relaxed) == FAR {
                d += 1;
                let front = &frontier;
                let next: Vec<Vec<u32>> = each_piece(cpu, front.len().div_ceil(FRONT), |p| {
                    let mut mine = Vec::new();
                    for &u in &front[p * FRONT..((p + 1) * FRONT).min(front.len())] {
                        let u = u as usize;
                        for a in r.start[u]..r.start[u + 1] {
                            let w = r.head[a] as usize;
                            if units.some(r.left[a])
                                && level[w].load(Relaxed) == FAR
                                && level[w].compare_exchange(FAR, d, Relaxed, Relaxed).is_ok()
                            {
                                mine.push(w as u32);
                            }
                        }
                    }
                    mine
                });
                frontier.clear();
                for x in next {
                    frontier.extend(x);
                }
            }
        }
        lv.copy_from_slice(&lvl);
        if lv[t] == FAR {
            break;
        }
        phases += 1;
        // 2. a blocking flow on the level graph
        for (v, c) in cur.iter_mut().enumerate() {
            *c = r.start[v];
        }
        path.clear();
        let mut v = s;
        loop {
            if v == t {
                let mut push = r.left[path[0]];
                for &a in &path[1..] {
                    push = units.min(push, r.left[a]);
                }
                let mut cut = path.len();
                for (i, &a) in path.iter().enumerate() {
                    r.left[a] = units.sub(r.left[a], push);
                    let m = r.mate[a] as usize;
                    r.left[m] = units.add(r.left[m], push);
                    if !units.some(r.left[a]) && cut == path.len() {
                        cut = i;
                    }
                }
                path.truncate(cut);
                v = path.last().map_or(s, |&a| r.head[a] as usize);
                continue;
            }
            let end = r.start[v + 1];
            let mut a = cur[v];
            while a < end {
                let w = r.head[a] as usize;
                if units.some(r.left[a]) && lv[w] == lv[v] + 1 {
                    break;
                }
                a += 1;
            }
            cur[v] = a;
            if a < end {
                path.push(a);
                v = r.head[a] as usize;
                continue;
            }
            // a dead end: left out for the rest of the phase
            lv[v] = FAR;
            match path.pop() {
                None => break,
                Some(a) => {
                    v = r.head[r.mate[a] as usize] as usize;
                    cur[v] += 1;
                }
            }
        }
    }
    (lv.iter().map(|&l| l != FAR).collect(), phases)
}