最大网络流算法 push-relabel 的 python实现

来源:互联网 发布:python 创建数组 编辑:程序博客网 时间:2024/05/22 09:40
#!/user/bin/python
#
PUSH-RELABEL ALGORITHM
#
Author Dan Liu
h=[]
e
=[]
f
=[]
#V=[0,1,2,3]
#
E=[(0,1),(1,2),(1,3),(0,2),(2,3)]
#
G=(V,E)
#
C={(0,1):3,(1,2):3,(1,3):1,(0,2):4,(2,3):5}
#
s=0
#
t=3
V=[0,1,2,3,4,5]
E
=[(0,1),(1,2),(1,3),(1,4),(0,2),(2,4),(3,5),(4,5)]
G
=(V,E)
C
={(0,1):3,(1,2):1,(1,3):3,(1,4):4,(0,2):2,(2,4):2,(3,5):2,(4,5):3}
s
=0
t
=5
Ef
=[]
cf
={}
def init_preflow(G,s):
    
for i in G[1]:
        
if i[0] ==s:
            i
=(i[1],i[0])            
        Ef.append(i)
        
    
for i in C.items():
        key
=i[0]
        
if i[0][0] == s:
            key
=(i[0][1],i[0][0])
        cf[key]
=i[1]
    
for u in G[0]:
        h.append(0)
        e.append(0)
    
for u in G[0]:
        l
=[]
        
for v in G[0]:            
            l.append(0)
        f.append(l)
    
for edge in G[1]:
        f[edge[0]][edge[
1]]=0
        f[edge[0]][edge[
1]]=0
    h[s]
=len(G[0])
    
for edge in G[1]:
        
if edge[0] == s:
            u
=edge[1]
            tmp
=C.get(edge)
            f[s][u]
=tmp
            f[u][s]
=-tmp
            e[u]
=tmp
            e[s]
-=tmp
            
            
    
print "h=",h
    
print "f=",f
    
print "e=",e

def push_flow(u,v):    
    df
=min(e[u],cf.get((u,v)))
    f[u][v]
+=df
    f[v][u]
=-f[u][v]
    e[u]
-=df
    e[v]
+=df
    cf[(u,v)]
-=df    
    
if cf[(u,v)]==0:
        Ef.remove((u,v))
    
def relabel(u):            
    Eh
=[]
    
for item in Ef:
        
if item[0]==u:
            Eh.append(h[item[
1]])
    h[u]
=1+min(Eh)
    
def check_e(e):
    
for i in range(len(V)):
        
if i != s and i != t:
            
if e[i] > 0:
                
return i
    
return -1

def check_push(u):
    
for item in cf.items():        
        
if (item[0][0]) == u and item[1>and (h[u]==(h[item[0][1]]+1)):
            
return item[0][1]
    
return -1

def check_relabel(u):
    
for item in Ef:
        
if item[0]==u:
            
if h[u]>h[item[1]]:
                
return 1
    
return -1

def generic_push_relabel(G):
    init_preflow(G,s)
    active_node
=check_e(e)
    
while active_node > 0:
        v
=check_push(active_node)
        is_high
=check_relabel(active_node)
        
if v != -1:
            
print active_node, v
            push_flow(active_node, v)
        
elif is_high == -1:
        
#else:
            relabel(active_node)
        
print e    
        active_node
=check_e(e)

generic_push_relabel(G)
print "h=",h
print "f=",f
print "e=",e
    
原创粉丝点击