网络流算法Dinic的Python实现

在上一篇我们提到了网络流算法Push-relabel,那是90年代提出的算法,算是比较新的,而现在要说的Dinic算法则是由以色列人Dinitz在冷战时期,即60-70年代提出的算法变种而来的,其算法复杂度为O(mn^2)。

Dinic算法主要思想也是基于FF算法的,改进的地方也是减少寻找增广路径的迭代次数。此处Dinitz大师引用了一个非常聪明的数据结构,Layer Network,分层网络,该结构是由BFS tree启发得到的,它跟BFS tree的区别在于,BFS tree只保存到每一层的一条边,这样就导致了利用BFS tree一次只能发现一条增广路径,而分层网络保存了到每一层的所有边,但层内的边不保存。

介绍完数据结构,开始讲算法的步骤了,1)从网络的剩余图中利用BFS宽度优先遍历技术生成分层网络。2)在分层网络中不断调用DFS生成增广路径,直到s不可到达t,这一步体现了Dinic算法贪心的特性。3)max_flow+=这次生成的所有增广路径的flow,重新生成剩余图,转1)。

源代码如下:

采用递归实现BFS和DFS,效率不高。

__author__ = 'xanxus'
nodeNum, edgeNum = 0, 0
arcs = []


class Arc(object):
    def __init__(self):
        self.src = -1
        self.dst = -1
        self.cap = -1


class Layer(object):
    def __init__(self):
        self.nodeSet = set()
        self.arcList = []


s, t = -1, -1
with open('demo.dimacs') as f:
    for line in f.readlines():
        line = line.strip()
        if line.startswith('p'):
            tokens = line.split(' ')
            nodeNum = int(tokens[2])
            edgeNum = tokens[3]
        if line.startswith('n'):
            tokens = line.split(' ')
            if tokens[2] == 's':
                s = int(tokens[1])
            if tokens[2] == 't':
                t = int(tokens[1])
        if line.startswith('a'):
            tokens = line.split(' ')
            arc = Arc()
            arc.src = int(tokens[1])
            arc.dst = int(tokens[2])
            arc.cap = int(tokens[3])
            arcs.append(arc)

nodes = [-1] * nodeNum
for i in range(s, t + 1):
    nodes[i - s] = i
adjacent_matrix = [[0 for i in range(nodeNum)] for j in range(nodeNum)]
for arc in arcs:
    adjacent_matrix[arc.src - s][arc.dst - s] = arc.cap


def getLayerNetwork(current, ln, augment_set):
    if t - s in ln[current].nodeSet:
        return
    for i in ln[current].nodeSet:
        augment_set.add(i)
        has_augment = False
        for j in range(len(adjacent_matrix)):
            if adjacent_matrix[i][j] != 0:
                if len(ln) == current + 1:
                    ln.append(Layer())
                if j not in augment_set and j not in ln[current].nodeSet:
                    has_augment = True
                    ln[current + 1].nodeSet.add(j)
                    arc = Arc()
                    arc.src, arc.dst, arc.cap = i, j, adjacent_matrix[i][j]
                    ln[current].arcList.append(arc)
        if not has_augment and (i != t - s or i != 0):
            augment_set.remove(i)
            filter(lambda x: x == i, ln[current].nodeSet)
            newArcList = []
            for arc in ln[current - 1].arcList:
                if arc.dst != i:
                    newArcList.append(arc)
            ln[current - 1].arcList = newArcList
    if len(ln) == current + 1:
        return
    getLayerNetwork(current + 1, ln, augment_set)


def get_path(layerNetwork, src, current, path):
    for arc in layerNetwork[current].arcList:
        if arc.src == src and arc.cap != 0:
            path.append(arc)
            get_path(layerNetwork, arc.dst, current + 1, path)
            return


def find_blocking_flow(layerNetwork):
    sum_flow = 0
    while (True):
        path = []
        get_path(layerNetwork, 0, 0, path)
        if path[-1].dst != t - s:
            break
        else:
            bottleneck = min([arc.cap for arc in path])
            for arc in path:
                arc.cap -= bottleneck
            sum_flow += bottleneck
    return sum_flow


max_flow = 0
while (True):
    layerNetwork = []
    firstLayer = Layer()
    firstLayer.nodeSet.add(0)
    layerNetwork.append(firstLayer)
    augment_set = set()
    augment_set.add(0)

    getLayerNetwork(0, layerNetwork, augment_set)
    if t - s not in layerNetwork[-1].nodeSet:
        break
    current_flow = find_blocking_flow(layerNetwork)
    if current_flow == 0:
        break
    else:
        max_flow += current_flow
        # add the backward arcs
        for layer in layerNetwork:
            for arc in layer.arcList:
                adjacent_matrix[arc.dst][arc.src] += adjacent_matrix[arc.src][arc.dst] - arc.cap
                adjacent_matrix[arc.src][arc.dst] = arc.cap
for arc in arcs:
    print 'f %d %d %d' % (arc.src, arc.dst, arc.cap - adjacent_matrix[arc.src - s][arc.dst - s])


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Dinic算法是一种用来解决最大问题的算法,它的核心思想是构建分层图和阻塞量的概念。通过多次增广路径的查找来找出最大。 在Python实现Dinic算法可以参考以下步骤: 1. 首先,需要定义一个图的类,包括节点数和邻接表等属性,用来存储图的结构。 2. 实现图的构建函数,根据边的信息添加邻接表。 3. 基于Dinic算法,需要实现一个辅助函数来在网络中查找增广路径。可以使用广度优先搜索(BFS)或深度优先搜索(DFS)来实现。通过不断搜索增广路径,直到找不到增广路径为止。 4. 实现Dinic算法的主函数,其中包括初始化量和残余网络,以及进行多次增广路径搜索的过程。 5. 在每一次增广路径搜索中,需要更新量和残余网络,并计算每一条边的容量。 6. 最后,需要输出最大的值。 以下是一种可能的实现方式: ```python class Graph: def __init__(self, nodes): self.nodes = nodes self.adjacency = [[] for _ in range(nodes)] def add_edge(self, u, v, capacity): self.adjacency[u].append([v, capacity, 0, len(self.adjacency[v])]) self.adjacency[v].append([u, 0, 0, len(self.adjacency[u]) - 1]) def bfs(self, start, end): # 使用BFS查找增广路径 level = [-1] * self.nodes level[start] = 0 queue = [start] while queue: current_node = queue.pop(0) for neighbor in self.adjacency[current_node]: if level[neighbor[0]] < 0 and neighbor[1] > neighbor[2]: # 更新节点的层级 level[neighbor[0]] = level[current_node] + 1 queue.append(neighbor[0]) return level[end] >= 0 def dfs(self, current_node, end, flow): # 使用DFS查找增广路径 if current_node == end: return flow while self.adjacency[current_node][current_edge[current_node]][1] <= self.adjacency[current_node][current_edge[current_node]][2]: current_edge[current_node] += 1 for i in range(current_edge[current_node], len(self.adjacency[current_node])): neighbor = self.adjacency[current_node][i] if level[neighbor[0]] == level[current_node] + 1 and neighbor[1] > neighbor[2]: min_flow = min(flow, neighbor[1] - neighbor[2]) temp_flow = self.dfs(neighbor[0], end, min_flow) if temp_flow > 0: neighbor[2] += temp_flow self.adjacency[neighbor[0]][neighbor[3]][2] -= temp_flow return temp_flow return 0 def dinic(self, start, end): level = [0] * self.nodes max_flow = 0 while self.bfs(start, end): current_edge = [0] * self.nodes while True: flow = self.dfs(start, end, float('inf')) if not flow: break max_flow += flow return max_flow g = Graph(4) g.add_edge(0, 1, 3) g.add_edge(0, 2, 2) g.add_edge(1, 2, 2) g.add_edge(1, 3, 1) g.add_edge(2, 3, 3) print("最大为:", g.dinic(0, 3)) ``` 这个实现中,以一个简单的图作为例子进行了测试。首先,创建一个有4个节点的图,然后添加边和容量。最后,通过调用dinic函数来计算最大的值,并将结果输出。 希望以上回答对你有所帮助,如果有任何问题需要进一步解答,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值