網絡流算法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])


發佈了96 篇原創文章 · 獲贊 86 · 訪問量 96萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章