蓝桥杯–最大流问题(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)
结果一部分会超时,再勉。