Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

bellmanford.gno

18.02 Kb · 552 lines
  1// Package bellmanford finds the cheapest route from one node to every other
  2// node of a weighted directed graph whose arcs may cost LESS than nothing, as
  3// a pure, reusable package.
  4//
  5// It is the Bellman-Ford algorithm: V-1 passes over the whole arc list, each
  6// pass relaxing every arc, stopping as soon as a pass changes nothing. That is
  7// O(V*E) against Dijkstra's O((V+E) log V), and the extra cost buys exactly
  8// one thing: a negative arc no longer produces a confidently wrong answer. A
  9// settle-and-never-revisit search reads a rebate, a refund or a subsidy as an
 10// ordinary cheap hop and misses that it reorders everything decided before it.
 11//
 12// It also answers the question a shortest-path routine can only answer when it
 13// is allowed to look twice: whether a shortest path EXISTS. Go round a cycle
 14// whose arcs sum to less than zero and the total keeps falling, so there is no
 15// cheapest route to anything that cycle reaches, only cheaper ones. Such nodes
 16// report [Unbounded] rather than a number, the cycle itself is handed back by
 17// [Result.Cycle], and nodes the cycle cannot reach keep their real distances.
 18// A realm pricing a route across its own fee table wants to be told that,
 19// loudly, rather than handed the distance after an arbitrary number of turns.
 20//
 21// The run is deterministic. Arcs are relaxed in the order they were added,
 22// every pass, and a relaxation that merely ties the incumbent never replaces
 23// it, so the predecessor chain Path walks is the same on every node that runs
 24// the code. A search that broke ties by map iteration order would make a
 25// Render differ between validators, which is a consensus bug rather than a
 26// cosmetic one.
 27//
 28// Where it differs from [p/moul/x/daily/dijkstra](/p/moul/x/daily/dijkstra/v0),
 29// which is the right tool whenever every weight is non-negative:
 30//
 31//   - Dist has no "unreachable" sentinel value. -1 is a legitimate distance
 32//     here, so the int returned alongside ok=false carries no meaning at all.
 33//   - Self-loops are allowed. A negative one is the smallest negative cycle
 34//     there is, and refusing it would hide a case rather than simplify one.
 35//   - There is no AddUndirected. A negative arc in both directions is a
 36//     negative cycle by construction, so the convenience would be a trap.
 37//
 38// A live demo of this package is at
 39// [r/moul/x/daily/bellmanforddemo](/r/moul/x/daily/bellmanforddemo/v0).
 40package bellmanford
 41
 42const (
 43	// MaxNodes bounds the graph so a caller can size gas up front.
 44	MaxNodes = 512
 45	// MaxEdges bounds the arcs for the same reason. The work is V*E in the
 46	// worst case, so these two caps are what make that worst case a number
 47	// rather than a hope.
 48	MaxEdges = 4000
 49	// MaxWeight bounds a single arc's cost, in either direction. The bound on
 50	// a distance is not a path's length times this: while a negative cycle is
 51	// still being relaxed, one pass can walk every one of MaxEdges arcs and the
 52	// run makes up to MaxNodes passes, so a distance can drift as far as
 53	// MaxNodes*MaxEdges*MaxWeight. driftBound below makes the compiler check
 54	// that product fits.
 55	MaxWeight = 1 << 40
 56)
 57
 58// driftBound is the furthest a distance can move during a run, cycle included:
 59// MaxNodes passes, each over at most MaxEdges arcs, each worth at most
 60// MaxWeight. It is a typed const so that raising any of the three caps past
 61// what an int64 holds fails to compile instead of wrapping a distance and
 62// silently reporting no negative cycle.
 63const driftBound int64 = MaxNodes * MaxEdges * MaxWeight
 64
 65// State is what a run can say about one node. It exists because "no distance"
 66// has two different causes here and they call for opposite reactions: nothing
 67// reaches the node, or too much does.
 68type State int
 69
 70const (
 71	// Unknown means the graph has never heard the name.
 72	Unknown State = iota
 73	// Unreached means no route leaves the source for it.
 74	Unreached
 75	// Settled means it has a finite cheapest route, which Dist returns.
 76	Settled
 77	// Unbounded means a negative cycle reaches it, so every route can be
 78	// beaten by going round once more and no cheapest route exists.
 79	Unbounded
 80)
 81
 82// String renders a State for a table or an error message.
 83func (s State) String() string {
 84	switch s {
 85	case Unknown:
 86		return "unknown"
 87	case Unreached:
 88		return "unreached"
 89	case Settled:
 90		return "settled"
 91	case Unbounded:
 92		return "unbounded"
 93	}
 94	return "invalid"
 95}
 96
 97type arc struct {
 98	from, to, weight int
 99}
100
101// Graph is a weighted directed graph over named nodes. The zero value is not
102// usable, build one with New.
103type Graph struct {
104	names []string       // node index -> name, in insertion order
105	index map[string]int // name -> node index. Looked up, never ranged over
106	arcs  []arc          // every arc, in insertion order: this is the relaxation order
107}
108
109// New returns an empty Graph.
110func New() *Graph { return &Graph{index: map[string]int{}} }
111
112// AddNode registers a node with no arcs and returns its index. Adding a node
113// twice returns the existing index and changes nothing, which is how a caller
114// declares an island that nothing reaches.
115//
116// It panics on an empty name, and past MaxNodes.
117func (g *Graph) AddNode(nm string) int {
118	if nm == "" {
119		panic("bellmanford: empty node name")
120	}
121	if i, ok := g.index[nm]; ok {
122		return i
123	}
124	if len(g.names) >= MaxNodes {
125		panic("bellmanford: too many nodes")
126	}
127	i := len(g.names)
128	g.names = append(g.names, nm)
129	g.index[nm] = i
130	return i
131}
132
133// AddEdge records a one-way arc from -> to costing weight, registering either
134// endpoint that is new. The weight may be negative, which is the whole reason
135// this package exists. Parallel arcs are kept rather than collapsed: the
136// search takes the cheapest, and dropping the others would lose information a
137// caller may want to render.
138//
139// A self-loop is legal. A negative one is a one-arc negative cycle and is
140// reported as such; a non-negative one can never improve a distance and is
141// simply never relaxed.
142//
143// It panics on a weight outside [-MaxWeight, MaxWeight], and past MaxEdges.
144func (g *Graph) AddEdge(from, to string, weight int) {
145	if weight > MaxWeight || weight < -MaxWeight {
146		panic("bellmanford: weight out of range")
147	}
148	if len(g.arcs) >= MaxEdges {
149		panic("bellmanford: too many edges")
150	}
151	f := g.AddNode(from)
152	t := g.AddNode(to)
153	g.arcs = append(g.arcs, arc{from: f, to: t, weight: weight})
154}
155
156// Len returns the number of nodes.
157func (g *Graph) Len() int { return len(g.names) }
158
159// Edges returns the number of arcs.
160func (g *Graph) Edges() int { return len(g.arcs) }
161
162// Names returns the node names in insertion order. The slice is a copy, so a
163// caller cannot reorder the graph's own index by sorting it.
164func (g *Graph) Names() []string {
165	out := make([]string, len(g.names))
166	copy(out, g.names)
167	return out
168}
169
170// Has reports whether the graph knows a node by that name.
171func (g *Graph) Has(nm string) bool {
172	_, ok := g.index[nm]
173	return ok
174}
175
176// Result holds one single-source run. It is a snapshot: mutating the graph
177// afterwards does not update it. It keeps its own views of the node names and
178// the arc list, capped at their length when From ran, so a node or an arc
179// added later is invisible to it rather than an index past its slices.
180type Result struct {
181	names     []string       // the graph's names as of From, capped
182	arcs      []arc          // the graph's arcs as of From, capped
183	index     map[string]int // shared with the graph: always bounds-check against names
184	src       int
185	dist      []int
186	prev      []int
187	reached   []bool
188	unbounded []bool
189	cycle     []int // a closed walk, first node repeated last. Empty when there is none
190	rounds    int
191	relaxs    int
192}
193
194// From runs the search outward from source and returns what every node is
195// worth. It panics when source is not in the graph, because a typo'd source
196// silently reporting "nothing is reachable" is the failure mode this package
197// exists to avoid.
198//
199// It never panics on a negative cycle. A cycle is an answer, not an error, and
200// the caller gets to decide what to do about it.
201func (g *Graph) From(source string) *Result {
202	s, ok := g.index[source]
203	if !ok {
204		panic("bellmanford: unknown source: " + source)
205	}
206
207	n := len(g.names)
208	// Both slices are only ever appended to, so a full-slice expression is a
209	// snapshot: a later append reallocates or writes past len, never inside it.
210	m := len(g.arcs)
211	r := &Result{names: g.names[:n:n], arcs: g.arcs[:m:m], index: g.index, src: s}
212	r.dist = make([]int, n)
213	r.prev = make([]int, n)
214	r.reached = make([]bool, n)
215	r.unbounded = make([]bool, n)
216	for i := 0; i < n; i++ {
217		r.prev[i] = -1
218	}
219	r.reached[s] = true
220
221	// Up to V-1 passes. A shortest path visits each node at most once, so it
222	// is at most V-1 arcs long, and one pass extends every known path by at
223	// least one arc. More passes than that can only mean a negative cycle.
224	stable := false
225	for pass := 0; pass < n-1; pass++ {
226		r.rounds++
227		if !r.relaxAll() {
228			stable = true
229			break
230		}
231	}
232
233	if stable {
234		// Nothing moved in the last pass, so nothing can move again and no
235		// negative cycle is reachable from here. Skip the detection pass
236		// rather than pay for it.
237		return r
238	}
239	r.detectCycle()
240	return r
241}
242
243// relaxAll makes one pass over the arc list and reports whether anything
244// improved. Arcs are visited in insertion order, every time: that is what
245// makes two runs of the same graph produce the same predecessors.
246func (r *Result) relaxAll() bool {
247	changed := false
248	for _, a := range r.arcs {
249		if !r.reached[a.from] {
250			continue
251		}
252		cand := r.dist[a.from] + a.weight
253		if !r.reached[a.to] {
254			r.reached[a.to] = true
255			r.dist[a.to] = cand
256			r.prev[a.to] = a.from
257			r.relaxs++
258			changed = true
259			continue
260		}
261		if cand < r.dist[a.to] {
262			// Strictly cheaper, never merely equal: a tie leaves the
263			// incumbent predecessor in place, which is what makes Path
264			// reproducible rather than dependent on arc order.
265			r.dist[a.to] = cand
266			r.prev[a.to] = a.from
267			r.relaxs++
268			changed = true
269		}
270	}
271	return changed
272}
273
274// detectCycle runs the one extra pass that proves the answer. Any arc still
275// able to improve a distance after V-1 passes is reachable from a negative
276// cycle, so its head is a witness: everything the witness reaches is
277// unbounded, and walking back from it lands on the cycle itself.
278func (r *Result) detectCycle() {
279	var witnesses []int
280	for _, a := range r.arcs {
281		if !r.reached[a.from] {
282			continue
283		}
284		cand := r.dist[a.from] + a.weight
285		if !r.reached[a.to] || cand < r.dist[a.to] {
286			// Point the witness at the arc that beat it, so the walk back
287			// below lands inside the cycle rather than beside it.
288			r.reached[a.to] = true
289			r.dist[a.to] = cand
290			r.prev[a.to] = a.from
291			witnesses = append(witnesses, a.to)
292		}
293	}
294	if len(witnesses) == 0 {
295		return
296	}
297
298	r.markUnbounded(witnesses)
299	r.cycle = r.walkBackToCycle(witnesses[0])
300}
301
302// markUnbounded floods forward from the witnesses. A node a negative cycle can
303// reach has no cheapest route, and that is true however far downstream it
304// sits, so the flood follows arcs rather than stopping at the cycle.
305func (r *Result) markUnbounded(witnesses []int) {
306	queue := make([]int, 0, len(r.names))
307	for _, w := range witnesses {
308		if !r.unbounded[w] {
309			r.unbounded[w] = true
310			queue = append(queue, w)
311		}
312	}
313	// An adjacency list built here rather than held on the Graph: this walk
314	// is the only thing that needs one, and only when a cycle exists.
315	adj := make([][]int, len(r.names))
316	for _, a := range r.arcs {
317		adj[a.from] = append(adj[a.from], a.to)
318	}
319	for len(queue) > 0 {
320		u := queue[len(queue)-1]
321		queue = queue[:len(queue)-1]
322		for _, v := range adj[u] {
323			if r.unbounded[v] {
324				continue
325			}
326			r.unbounded[v] = true
327			queue = append(queue, v)
328		}
329	}
330}
331
332// walkBackToCycle returns the negative cycle a witness sits downstream of, as
333// a closed walk with the first node repeated last.
334//
335// Stepping back V times from a witness cannot leave the cycle: the witness is
336// reachable from one, the predecessor chain enters it and never leaves, and V
337// steps is more than the cycle is long. From there the chain is the cycle.
338func (r *Result) walkBackToCycle(witness int) []int {
339	at := witness
340	for i := 0; i < len(r.names); i++ {
341		if r.prev[at] == -1 {
342			// Not reachable, so not a cycle. Defensive: a witness always has
343			// a predecessor, by the assignment in detectCycle.
344			return nil
345		}
346		at = r.prev[at]
347	}
348
349	var rev []int
350	start := at
351	for {
352		rev = append(rev, at)
353		at = r.prev[at]
354		if at == start || at == -1 || len(rev) > len(r.names) {
355			break
356		}
357	}
358	if at != start {
359		return nil
360	}
361
362	out := make([]int, 0, len(rev)+1)
363	for i := len(rev) - 1; i >= 0; i-- {
364		out = append(out, rev[i])
365	}
366	return append(out, out[0])
367}
368
369// at returns the index of a node State has already called Settled.
370func (r *Result) at(nm string) int { return r.index[nm] }
371
372// Source returns the node the run started from.
373func (r *Result) Source() string { return r.names[r.src] }
374
375// State reports what the run can say about one node. It is the call to make
376// before Dist whenever the difference between "nothing reaches it" and "a
377// negative cycle reaches it" changes what the caller does.
378func (r *Result) State(nm string) State {
379	i, known := r.index[nm]
380	if !known || i >= len(r.names) {
381		// A name the graph learned after From is unknown to this run: the
382		// index is shared, but the Result's own slices stop at its snapshot.
383		return Unknown
384	}
385	if r.unbounded[i] {
386		return Unbounded
387	}
388	if !r.reached[i] {
389		return Unreached
390	}
391	return Settled
392}
393
394// Dist returns the total weight of the cheapest route to nm, and whether one
395// exists at all.
396//
397// The int returned with ok=false means NOTHING. There is no sentinel because
398// there cannot be one: a negative total is a legitimate answer here, so any
399// value this could return is also a value a real route could have. Call State
400// when the reason matters.
401func (r *Result) Dist(nm string) (int, bool) {
402	if r.State(nm) != Settled {
403		return 0, false
404	}
405	return r.dist[r.at(nm)], true
406}
407
408// Path returns the cheapest route to nm, source first and nm last. It returns
409// nil whenever Dist would return ok=false, the unbounded case included: a
410// route that can always be beaten is not a shortest path, and handing one back
411// would be the lie this package is built to refuse.
412func (r *Result) Path(nm string) []string {
413	if r.State(nm) != Settled {
414		return nil
415	}
416	var rev []int
417	for at := r.at(nm); at != -1; at = r.prev[at] {
418		rev = append(rev, at)
419	}
420	out := make([]string, len(rev))
421	for k, at := range rev {
422		out[len(rev)-1-k] = r.names[at]
423	}
424	return out
425}
426
427// PathString renders Path joined with sep, or "" when there is no route. It
428// exists so a Render does not have to carry its own join loop.
429func (r *Result) PathString(nm, sep string) string {
430	p := r.Path(nm)
431	if p == nil {
432		return ""
433	}
434	return join(p, sep)
435}
436
437// Via returns the node immediately before nm on the cheapest route, and false
438// for the source and for anything without one.
439func (r *Result) Via(nm string) (string, bool) {
440	if r.State(nm) != Settled {
441		return "", false
442	}
443	p := r.prev[r.at(nm)]
444	if p == -1 {
445		return "", false
446	}
447	return r.names[p], true
448}
449
450// Reachable returns how many nodes a route leaves the source for, the source
451// included and the unbounded ones counted: they are reached, they just have no
452// cheapest route.
453func (r *Result) Reachable() int {
454	count := 0
455	for _, ok := range r.reached {
456		if ok {
457			count++
458		}
459	}
460	return count
461}
462
463// Rounds returns how many passes over the arc list the run made. The bound is
464// V-1, and what decides the real figure is the order the arcs were added in,
465// so this is the number to watch when gas matters.
466//
467// A run that settles early makes one more pass to prove nothing moved, and
468// that pass is counted here. A run that needs the full V-1 instead pays the
469// separate detection pass, which is not.
470func (r *Result) Rounds() int { return r.rounds }
471
472// Relaxations returns how many arcs actually improved a distance. It is the
473// honest cost figure: the arc count times the round count is what was looked
474// at, this is what was paid for.
475func (r *Result) Relaxations() int { return r.relaxs }
476
477// HasNegativeCycle reports whether a cycle whose arcs sum to less than zero is
478// reachable from the source. A cycle elsewhere in the graph is not this run's
479// problem and is not reported.
480func (r *Result) HasNegativeCycle() bool { return len(r.cycle) > 0 }
481
482// Cycle returns one negative cycle as a closed walk, first node repeated last,
483// or nil when there is none. A graph may hold several; this is the one the
484// first witness in arc order sits downstream of.
485func (r *Result) Cycle() []string {
486	if len(r.cycle) == 0 {
487		return nil
488	}
489	out := make([]string, len(r.cycle))
490	for i, at := range r.cycle {
491		out[i] = r.names[at]
492	}
493	return out
494}
495
496// CycleWeight returns what one turn of the reported cycle costs, taking the
497// cheapest arc for each hop, or 0 when there is no cycle. It is always
498// negative when HasNegativeCycle is true, and that is worth asserting in a
499// caller's test: it is the one number that proves the detection was real.
500func (r *Result) CycleWeight() int {
501	if len(r.cycle) < 2 {
502		return 0
503	}
504	total := 0
505	for i := 0; i+1 < len(r.cycle); i++ {
506		total += r.cheapestArc(r.cycle[i], r.cycle[i+1])
507	}
508	return total
509}
510
511// cheapestArc returns the lowest weight among the arcs from -> to. The walk
512// came from the predecessor chain, so at least one such arc always exists.
513func (r *Result) cheapestArc(from, to int) int {
514	best := 0
515	found := false
516	for _, a := range r.arcs {
517		if a.from != from || a.to != to {
518			continue
519		}
520		if !found || a.weight < best {
521			best = a.weight
522			found = true
523		}
524	}
525	return best
526}
527
528// UnboundedNodes returns, in insertion order, every node a negative cycle
529// reaches. It is empty when there is no cycle, and it is the blast radius: the
530// nodes whose distance a less careful implementation would have reported.
531func (r *Result) UnboundedNodes() []string {
532	var out []string
533	for i, u := range r.unbounded {
534		if u {
535			out = append(out, r.names[i])
536		}
537	}
538	return out
539}
540
541// join concatenates with a separator. Written out rather than imported so the
542// package keeps no dependency at all, not even strings.
543func join(in []string, sep string) string {
544	out := ""
545	for i, s := range in {
546		if i > 0 {
547			out += sep
548		}
549		out += s
550	}
551	return out
552}