Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions binary_tree/LCA_in_binary_tree.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
# Lowest Common Ancestor in a Binary Tree


class Node:

def __init__(self, key):
self.key = key
self.left = None
self.right = None


def find_path(root, path, k):
if root is None:
return False

path.append(root.key)

if root.key == k:
return True

if ((root.left is not None and find_path(root.left, path, k)) or
(root.right is not None and find_path(root.right, path, k))):
return True

path.pop()
return False


def LCA(root, n1, n2):
path1 = []
path2 = []

if not find_path(root, path1, n1) or not find_path(root, path2, n2):
return -1

i = 0
while i < len(path1) and i < len(path2):
if path1[i] != path2[i]:
break
i += 1
return path1[i - 1]


root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.left.left.left = Node(8)
root.left.left.right = Node(9)
root.left.right.left = Node(10)
root.left.right.right = Node(11)
root.right.left.left = Node(12)
root.right.left.right = Node(13)
root.right.right.left = Node(14)
root.right.right.right = Node(15)

print("LCA(10, 11) = " + str(LCA(root, 10, 11)))

print("LCA(12, 15) = " + str(LCA(root, 12, 15)))

print("LCA(7, 13) = " + str(LCA(root, 7, 13)))

print("LCA(5, 14) = " + str(LCA(root, 5, 14)))
49 changes: 49 additions & 0 deletions networking_flow/dinic.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
# Dinic Algorithm


def bfs(matrix_capacity, matrix_flow, s, t):
n = len(matrix_capacity)
queue = [s]
global level
level = n * [0]
level[s] = 1
while queue:
k = queue.pop(0)
for i in range(n):
if (matrix_flow[k][i] < matrix_capacity[k][i]) and (level[i] == 0):
level[i] = level[k] + 1
queue.append(i)
return level[t] > 0


def dfs(matrix_capacity, matrix_flow, k, cp):
tmp = cp
if k == len(matrix_capacity) - 1:
return cp
for i in range(len(matrix_capacity)):
if (level[i] == level[k] + 1) and (matrix_flow[k][i] < matrix_capacity[k][i]):
f = dfs(matrix_capacity, matrix_flow, i, min(tmp, matrix_capacity[k][i] - matrix_flow[k][i]))
matrix_flow[k][i] = matrix_flow[k][i] + f
matrix_flow[i][k] = matrix_flow[i][k] - f
tmp = tmp - f
return cp - tmp


def max_flow(graph, s, t):
n = len(graph)
matrix_flow = [n * [0] for _ in range(n)] # F is the flow matrix
flow = 0
while bfs(graph, matrix_flow, s, t):
flow = flow + dfs(graph, matrix_flow, s, 100000)
return flow


graph = [[0, 16, 13, 0, 0, 0],
[0, 0, 10, 12, 0, 0],
[0, 4, 0, 0, 14, 0, 0],
[0, 0, 9, 0, 0, 20],
[0, 0, 0, 7, 0, 4],
[0, 0, 0, 0, 0, 0]]

source, sink = 0, 5
print(max_flow(graph, source, sink))