Python中的Ford-Fulkerson Max Flow实现

时间:2017-01-27 09:26:07

标签: algorithm ford-fulkerson

这是我的python代码,用于在具有源S和接收器D的多接收器,多源图(E)上执行Ford-Fulkerson操作 流过的最大值是200万。我使用虚拟源和虚拟接收器来解决这个问题。我知道我设置了虚拟源并向右下沉。因为我的代码通过,如果我使用Geek的geek的实现,但我真的想了解为什么我的工作不起作用。有人有建议吗?

i_sources = len(E)
n = i_sources +1
x = [[0]*(len(E[0])+2)  for i in range(len(E)+2)]
for i in range(0, len(E)):
    E[i] += [0,0]
E += [[0]*len(E[0]) for i in range(2)]
for s in S: # set sources
    E[i_sources][s] = 2000000
for d in D: # set Drains
    E[d][n] = 2000000

l = [None]*len(E)
l[i_sources] = [float('Inf'), None, None]
q = [i_sources]
while(q != []):  # queue not empty
    i = q.pop(0)
    for j in range(0, len(E)):   # forward links
        if(l[j] == None and j != i and E[i][j] != 0):
            r = E[i][j]-x[i][j]
            if r>0:
                l[j] = [min(l[i][0], r), i, '+']

                q.append(j)
    for j in range(0, len(E)):   #reverse links
        if(l[j] == None and j != i and E[i][j] != 0):
            if x[j][i]>0:
                l[j] = [min(l[i][0], x[j][i]), i, '-']
                q.append(j)
    if(l[n] != None):  # backtrack if needed
        j = n
        while (j != i_sources):
            i = abs(l[j][1])
            if(l[j][2] == '+'):
                x[i][j] += l[n][0]
            else:
                x[j][i] -= l[n][0]
            j=i
        l = [None]*len(E)
        l[i_sources] = [float('Inf'), None, None]
        q = [i_sources]
sum_x = 0
for i in range(0, n):
    sum_x += x[i][n]
return min(sum_x, 2000000)

0 个答案:

没有答案