realsdx

fordmy

Sep 2nd, 2019
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.45 KB | None | 0 0
  1. def bfs(n, adj_mat, s, t, parent):
  2.         visited =[False]*n      
  3.         queue=[]
  4.          
  5.         queue.append(s)
  6.         visited[s] = True
  7.            
  8.         while queue:
  9.             u = queue.pop(0)
  10.          
  11.      
  12.         for ind, val in enumerate(adj_mat[u]):
  13.             if visited[ind] == False and val > 0 :
  14.                     queue.append(ind)
  15.                     visited[ind] = True
  16.                     parent[ind] = u
  17.  
  18.         return True if visited[t] else False
  19.        
  20. def fordfulkerson(n, adj_mat, s, t):
  21.         parent = [-1]*(n)
  22.  
  23.         max_flow = 0
  24.  
  25.         while bfs(n, adj_mat, s, t, parent) :
  26.  
  27.             path_flow = float("Inf")
  28.             u = t
  29.             while(u !=  s):
  30.                 path_flow = min(path_flow, adj_mat[parent[u]][u])
  31.                 u = parent[u]
  32.  
  33.             max_flow +=  path_flow
  34.  
  35.             v = sink
  36.             while(v !=  source):
  37.                 u = parent[v]
  38.                 adj_mat[u][v] -= path_flow
  39.                 adj_mat[v][u] += path_flow
  40.                 v = parent[v]
  41.  
  42.         return max_flow
  43.  
  44.  
  45. n=int(input("ENter the numbers of nodes: "))
  46. adj_mat = [[0]*(n+1) for i in range(n+1)]
  47. m=int(input("ENter number of edges: "))
  48.  
  49. for _ in range(m):
  50.     x, y, f=eval(input("Enter edge and capacity: "))
  51.     adj_mat[x][y]=f
  52.  
  53. source, sink = map(int, input("Enter source and sink: "))
  54.    
  55. print("MAX: ", fordfulkerson(n, adj_mat, source, sink)
Add Comment
Please, Sign In to add comment