最大流算法

最大流问题综述:源节点s ,目的地t,从源节点s和t  之间 ,可以流动的最大量是多少。

s和t之间的每一条边f(u,v)/c(u,v)  表示分开流 和容量

残存网络: 给定流网络G和流量f ,残存网络Gf 由那些仍有空间对流量进行调整的边构成。一条边所能许可的反向流量最多将其正向流量抵消,

3;代码:

NODE_SIZE = 10
capacity = [ [ 0 for i in range( NODE_SIZE ) ] for j in range( NODE_SIZE ) ]
parent = [ -1 for i in range( NODE_SIZE ) ]
visited = [ False for i in range( NODE_SIZE ) ]

def edmonds_karp( start, end ):
    Q = []
    global visited
    visited = [ False for i in range
                ( NODE_SIZE ) ]

    visited[start] = True
    Q.append( start )

    while len( Q ) != 0:
        temp = Q.pop( 0 )
        for i in range( NODE_SIZE ):
            if capacity[temp][i] and not visited[i]:
                print("temp:",temp,"i:",i)
                visited[i] = True
                parent[i] = temp
                Q.append( i )
                if i == end:

                    print()
                    return True
    return False

def ford_fulkerson( start, end ):
    max_flow = 0
    while True:
        if not edmonds_karp( start, end ):
            print("break")
            break
        
        flow = float( "inf" )
        path_node = end
        
        while path_node != start:
            flow = min( flow, capacity[parent[path_node]][path_node] )
            path_node = parent[path_node]
            print("flow:",flow,"parent[path_node]:",parent[path_node],"path_node :",path_node)
           
        path_node = end
        while path_node != start:
            capacity[path_node][parent[path_node]] += flow
            capacity[parent[path_node]][path_node] -= flow
            print("path_node:",path_node,"parent[path_node]:",parent[path_node])
            path_node = parent[path_node]
            
        max_flow += flow
    return max_flow

nodes, edges = map( lambda x: int( x ), input( "Enter number of nodes and edges: " ).split( " " ) )

for e in range( edges ):
    u, v, cap = map( lambda x: int( x ), input( "Enter u, v and capacity: " ).split( " " ) )
    capacity[u][v] = cap
    
start, end = map( lambda x: int( x ), input( "Enter start_node and end_node: " ).split( " " ) )
max_flow = ford_fulkerson( start, end )
print( "max flow: ", max_flow )

 输入:

1: 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值