Pagini recente » Cod sursa (job #3310376) | Cod sursa (job #3323788) | Monitorul de evaluare | Cod sursa (job #1823988) | Cod sursa (job #3328612)
def bfs(s, d, n, G, capacitate, flux):
coada = []
vis = [0] *(n+1)
p = [0]*(n+1)
coada.append(s)
vis[s] = 1
while len(coada) > 0 :
nod = coada.pop(0)
for vecin in G[nod]:
if not vis[vecin] and capacitate[nod][vecin] - flux[nod][vecin] > 0:
vis[vecin] = 1
p[vecin] = nod
coada.append(vecin)
if vecin == d:
break
if not vis[d]:
return 0
path = []
x = d
while x != 0:
path.append(x)
x = p[x]
path.reverse()
flow_path = float('inf')
for i in range(len(path)-1):
u = path[i]
v = path[i+1]
flow_path = min(flow_path, capacitate[u][v] - flux[u][v])
for i in range(len(path) - 1):
u = path[i]
v = path[i + 1]
flux[u][v] += flow_path
flux[v][u] -= flow_path
return flow_path
def citire():
with open("maxflow.in",'r') as file:
for i,line in enumerate(file):
if i == 0:
n , m = map(int,line.split())
capacitate = [[0]*(n+1) for _ in range(n+1)]
flux = [[0]*(n+1) for _ in range(n+1)]
G = [[] for _ in range(n+1)]
else:
x , y , c = map(int,line.split())
capacitate[x][y] = c
G[x].append(y)
G[y].append(x)
return n, m, G, capacitate, flux
def main():
date = citire()
n, m, G, capacitate, flux = citire()
max_flow = 0
while True:
flow_curent = bfs(1,n,n,G,capacitate,flux)
if flow_curent == 0:
break
max_flow += flow_curent
with open('maxflow.out','w') as file:
file.write(str(max_flow))
main()