我正在尝试使用Ford-Fulkerson算法解决图的最大流问题。该算法仅用有向图描述。当图表无向时怎么办?
我模仿无向图的方法是在一对顶点之间使用两个有向边。令我感到困惑的是:这些边缘中的每一个都应该有剩余边缘,还是剩余边缘的“相对”有向边缘?
我已经假设了最后一个但我的算法似乎进入了无限循环。我希望你们中的任何人能给我一些帮助。以下是我自己的实现。我在find中使用DFS。
import sys
import fileinput
class Vertex(object):
def __init__(self, name):
self.name = name
self.edges = []
def find(self, sink, path):
if(self == sink):
return path
for edge in self.edges:
residual = edge.capacity - edge.flow
if(residual > 0 or edge.inf):
if(edge not in path and edge.oppositeEdge not in path):
toVertex = edge.toVertex
path.append(edge)
result = toVertex.find(sink, path)
if result != None:
return result
class Edge(object):
def __init__(self, fromVertex, toVertex, capacity):
self.fromVertex = fromVertex
self.toVertex = toVertex
self.capacity = capacity
self.flow = 0
self.inf = False
if(capacity == -1):
self.inf = True
def __repr__(self):
return self.fromVertex.name.strip() + " - " + self.toVertex.name.strip()
def buildGraph(vertices, edges):
for edge in edges:
sourceVertex = vertices[int(edge[0])]
sinkVertex = vertices[int(edge[1])]
capacity = int(edge[2])
edge1 = Edge(sourceVertex, sinkVertex, capacity)
edge2 = Edge(sinkVertex, sourceVertex, capacity)
sourceVertex.edges.append(edge1)
sinkVertex.edges.append(edge2)
edge1.oppositeEdge = edge2
edge2.oppositeEdge = edge1
def maxFlow(source, sink):
path = source.find(sink, [])
while path != None:
minCap = sys.maxint
for e in path:
if(e.capacity < minCap and not e.inf):
minCap = e.capacity
for edge in path:
edge.flow += minCap
edge.oppositeEdge.flow -= minCap
path = source.find(sink, [])
return sum(e.flow for e in source.edges)
vertices, edges = parse()
buildGraph(vertices, edges)
source = vertices[0]
sink = vertices[len(vertices)-1]
maxFlow = maxFlow(source, sink)
答案 0 :(得分:11)
使用两个反平行边的方法有效。如果您的边缘是a->b
(容量10,我们在其上发送7),我们会引入一个新的剩余边(从b
到a
,剩余容量为17,剩余边距来自{ {1}}至a
具有剩余容量3)。
原始后边缘(从b
到b
)可以原样保留,或者新的剩余边缘和原始背景可以融化到一个边缘。
我可以想象,将剩余容量添加到原始后端有点简单,但不确定。