蓝桥杯--最大流问题

蓝桥杯–最大流问题(python)

问题描述

资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
  一个有向图,求1到N的最大流
输入格式
  第一行N M,表示点数与边数
  接下来M行每行s t c表示一条从s到t的容量为c的边
输出格式
  一个数最大流量
样例输入
6 10
1 2 4
1 3 8
2 3 4
2 4 4
2 5 1
3 4 2
3 5 2
4 6 7
5 4 6
5 6 3
样例输出
8

数据约定:
n<=1000 m<=10000

代码

n,m = list(map(int,input().split()))

dp = [[0 for j in range(m+1)] for i in range(m+1)]

for i in range(m):
    s, t, c = list(map(int, input().split()))
    dp[s][t] += c

def BFS(dp,s,t,path):
    for i in range(len(path)):
        path[i] = 0
    vis = [0 for i in range(m+1)]
    vis[s] = 1
    q = []
    q.append(s)
    while len(q)!=0:
        tmp = q.pop(0)
        for i in range(1,m+1):
            if dp[tmp][i] > 0 and vis[i] == 0:
                q.append(i)
                vis[i] = 1
                path[i] = tmp
    return vis[t] == 1

def minC(path,dp):
    min_ = dp[path[len(path)-1]][len(path)-1]
    i = len(path)-2
    while i != 1:
        if dp[path[i]][i] < min_ and dp[path[i]][i] > 0:
            min_ = dp[path[i]][i]
        i = path[i]
    return min_

path = [0]*(n+1)
flow = 0

while BFS(dp,1,n,path):
    min_capacity = minC(path,dp)
    flow += min_capacity
    i=n
    while i!= 1:
        j = path[i]
        dp[j][i] -= min_capacity
        dp[i][j] += min_capacity
        i = path[i]

print(flow)

结果一部分会超时,再勉。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值