Debian Codegraph @

maxflow.go

raw symbols SCIP
1 package graph
2
3 // MaxFlow computes a maximum flow from s to t in a graph
4 // with nonnegative edge capacities.
5 // The time complexity is O(|E|²⋅|V|), where |E| is the number of edges
6 // and |V| the number of vertices in the graph.
7 func MaxFlow(g Iterator, s, t int) (flow int64, graph Iterator) {
8 // Edmonds-Karp's algorithm
9 n := g.Order()
10 prev := make([]int, n)
11 residual := Copy(g)
12 for residualFlow(residual, s, t, prev) && flow < Max {
13 pathFlow := Max
14 for v := t; v != s; {
15 u := prev[v]
16 if c := residual.Cost(u, v); c < pathFlow {
17 pathFlow = c
18 }
19 v = u
20 }
21 flow += pathFlow
22 for v := t; v != s; {
23 u := prev[v]
24 residual.AddCost(u, v, residual.Cost(u, v)-pathFlow)
25 residual.AddCost(v, u, residual.Cost(v, u)+pathFlow)
26 v = u
27 }
28 }
29 res := New(n)
30 for v := 0; v < n; v++ {
31 g.Visit(v, func(w int, c int64) (skip bool) {
32 if flow := c - residual.Cost(v, w); flow > 0 {
33 res.AddCost(v, w, flow)
34 }
35 return
36 })
37 }
38 return flow, Sort(res)
39 }
40
41 func residualFlow(g *Mutable, s, t int, prev []int) bool {
42 visited := make([]bool, g.Order())
43 prev[s], visited[s] = -1, true
44 for queue := []int{s}; len(queue) > 0; {
45 v := queue[0]
46 queue = queue[1:]
47 g.Visit(v, func(w int, c int64) (skip bool) {
48 if !visited[w] && c > 0 {
49 prev[w] = v
50 visited[w] = true
51 queue = append(queue, w)
52 }
53 return
54 })
55 }
56 return visited[t]
57 }