图 - 最大流

#!/usr/bin/env python3.3
# -*- coding:utf-8 -*-
# Copyright 2013

'''
最大流:沿增广路径反复增加流,直到找不到增广路径
1)残留网络:Gf由可以容纳更多网络流的边所组成
2)增广路径:为残留网络Gf上从s到t的一条简单路径p,其中p中所的边的最小权值为该增广路径的残留容量
3)最大流最小割:对G的某个割(S,T),有|f|=c(S,T)
'''

def edmonds_karp(graph, graph_size, s, t):
    # 初始化所有边的流
    flow = [[0] * graph_size for i in range(graph_size)]
    while True:
        # 查找增广路径
        path = augmenting_path(graph, graph_size, flow, s, t)
        if path is not None:
            f = min(graph[u][v]-flow[u][v] for u, v in path)
            for u, v in path:
                flow[u][v] += f
                flow[v][u] -= f
        else:
            break
    return sum(flow[s])

def augmenting_path(graph, graph_size, flow, s, t):
    visit_q = [s]
    visit_path = {s:[]}
    while visit_q:
        # 广度优先搜索
        u = visit_q.pop(0)
        for v in range(graph_size):
            if v not in visit_path and graph[u][v] is not None:
                # 是否还有残留容量
                if graph[u][v] - flow[u][v] > 0:
                    visit_path[v] = visit_path[u] + [(u, v)]
                    if v == t:
                        return visit_path[v]
                    visit_q.append(v)
    return None

 

posted @ 2013-04-30 01:36  Leung文  阅读(172)  评论(0编辑  收藏  举报