Advertisement
anuar2k

Untitled

Jul 2nd, 2020
1,304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. import math
  2.  
  3. class Queue:
  4.     def __init__(self, capacity):
  5.         self.capacity = capacity
  6.         self.storage = [None] * (self.capacity + 1)
  7.         self.head = 0
  8.         self.tail = 0
  9.  
  10.     def enqueue(self, x):
  11.         if (self.head - self.tail) % len(self.storage) == self.capacity:
  12.             raise Exception("Queue is full")
  13.  
  14.         self.storage[self.head] = x
  15.         self.head = (self.head + 1) % len(self.storage)
  16.  
  17.     def dequeue(self):
  18.         result = self.storage[self.tail]
  19.         self.tail = (self.tail + 1) % len(self.storage)
  20.  
  21.         return result
  22.  
  23.     def is_empty(self):
  24.         return self.head == self.tail
  25.  
  26. def capacity(graph, flow, u, v):
  27.     result = 0
  28.  
  29.     if graph[u][v] > 0:
  30.         result = graph[u][v] - flow[u][v]
  31.     if graph[v][u] > 0:
  32.         result = flow[v][u]
  33.        
  34.     return result
  35.  
  36. def bfs(graph, flow, source, target):
  37.     q = Queue(len(graph))
  38.  
  39.     q.enqueue((source, None))
  40.  
  41.     parent_map = [None] * len(graph)
  42.     visited = [False] * len(graph)
  43.  
  44.     while not q.is_empty():
  45.         u, parent = q.dequeue()
  46.         parent_map[u] = parent
  47.         visited[u] = True
  48.         for v in range(len(graph)):
  49.             if not visited[v] and capacity(graph, flow, u, v) > 0:
  50.                 q.enqueue((v, u))
  51.  
  52.     return parent_map
  53.  
  54. def max_flow(graph, source, target):
  55.     flow = [[0] * len(graph) for _ in range(len(graph))]
  56.  
  57.     while (parent_map := bfs(graph, flow, source, target))[target] is not None:
  58.         u = parent_map[target]
  59.         v = target
  60.         min_capacity = math.inf
  61.  
  62.         while u is not None:
  63.             c = capacity(graph, flow, u, v)
  64.  
  65.             if c < min_capacity:
  66.                 min_capacity = c
  67.  
  68.             u = parent_map[u]
  69.             v = parent_map[v]
  70.  
  71.         u = parent_map[target]
  72.         v = target
  73.  
  74.         while u is not None:
  75.             if graph[u][v] > 0:
  76.                 flow[u][v] = flow[u][v] + min_capacity
  77.             else:
  78.                 flow[v][u] = flow[v][u] - min_capacity
  79.  
  80.             u = parent_map[u]
  81.             v = parent_map[v]
  82.  
  83.     return flow
  84.  
  85. graph = [
  86.     [0, 80, 10, 0],
  87.     [0, 0, 50, 20],
  88.     [0, 0, 0, 80],
  89.     [0, 0, 0, 0]
  90. ]
  91.  
  92. print(max_flow(graph, 0, 3))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement