最大流

本示例展示了如何使用 igraph.Graph.maxflow() 在有向图上构建具有边容量的最大流。

import igraph as ig
import matplotlib.pyplot as plt

首先,我们生成一个图并为每条边分配一个“容量”

g = ig.Graph(
    6,
    [(3, 2), (3, 4), (2, 1), (4,1), (4, 5), (1, 0), (5, 0)],
    directed=True
)
g.es["capacity"] = [7, 8, 1, 2, 3, 4, 5]

要查找最大流,我们可以简单地运行

flow = g.maxflow(3, 0, capacity=g.es["capacity"])

print("Max flow:", flow.value)
print("Edge assignments:", flow.flow)

# Output:
# Max flow: 6.0
# Edge assignments [1.0, 5.0, 1.0, 2.0, 3.0, 3.0, 3.0]
Max flow: 6.0
Edge assignments: [1.0, 5.0, 1.0, 2.0, 3.0, 3.0, 3.0]

最后,我们可以绘制有向图来查看情况

fig, ax = plt.subplots()
ig.plot(
    g,
    target=ax,
    layout="circle",
    vertex_label=range(g.vcount()),
    vertex_color="lightblue"
)
plt.show()
maxflow

脚本总运行时间: (0 分 0.063 秒)

此图库由 Sphinx-Gallery 生成