首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Maximum flow - Ford-Fulkerson:无向图

Maximum flow - Ford-Fulkerson:无向图
EN

Stack Overflow用户
提问于 2011-10-07 21:10:05
回答 1查看 17.8K关注 0票数 18

我正在尝试使用Ford-Fulkerson算法来解决图的最大流问题。该算法仅用有向图描述。当图是无向图的时候呢?

我所做的是在一对顶点之间使用两条有向边来模拟无向图。让我困惑的是:这些边缘中的每一条都应该有残差边缘,还是“相反”的定向边缘是残差边缘?

我假设了最后一个,但我的算法似乎在无限循环中进行。我希望你们中的任何人能给我一些帮助。下面是我自己的实现。我正在使用find中的DFS。

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-07 21:39:26

你的方法使用两条反平行的边是可行的。如果你的边是a->b (容量10,我们通过它发送7),我们引入一个新的剩余边(从ba,具有剩余容量17,从ab的剩余边具有剩余容量3)。

原始后边缘(从ba)可以保持原样,也可以将新的剩余边缘和原始backedge熔化成一条边。

我可以想象将剩余容量添加到原始后台边缘会更简单,但不确定这一点。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7687732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档