├── .gitignore ├── README.md ├── Week 2 ├── myout.txt ├── Antman-W2A1.py ├── Jobs-W2A2.py ├── tempCodeRunnerFile.py └── ArrTransfrom-W3A2.py ├── Week 9 ├── A1-Race.bin └── A1-Race.cpp ├── Week 10 ├── A1-Robbery.py └── A2-BeautifulSequence.py ├── Week 4 ├── A2-CityStates.py ├── A1-ArrayPermutation.py └── test1.py ├── Week 6 ├── A2-BusRoute.py └── A1-FriendsHouse.py ├── Week 3 └── ArraryOP-W3A1.py ├── Week 5 ├── A1-TheTrainRoute.py ├── A2-BeautifyImage.py └── test1.py ├── Week 7 └── A1-DigitalIndia.py └── Week 8 ├── temp.py └── A1-MaxFlow.py /.gitignore: -------------------------------------------------------------------------------- 1 | Competetive Programming.code-workspace 2 | .cph 3 | test.* -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NPTEL-Course-Getting-started-with-Competitive-Programming 2 | -------------------------------------------------------------------------------- /Week 2/myout.txt: -------------------------------------------------------------------------------- 1 | YES 2 | YES 3 | YES 4 | YES 5 | NO 6 | NO 7 | YES 8 | YES 9 | YES 10 | -------------------------------------------------------------------------------- /Week 9/A1-Race.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Md-Awaf/NPTEL-Course-Getting-started-with-Competitive-Programming/HEAD/Week 9/A1-Race.bin -------------------------------------------------------------------------------- /Week 10/A1-Robbery.py: -------------------------------------------------------------------------------- 1 | def solve(n, value): 2 | rob1, rob2 = 0, 0 3 | for i in value: 4 | temp = max(i + rob1, rob2) 5 | rob1 = rob2 6 | rob2 = temp 7 | return rob2 8 | t = int(input()) 9 | for _ in range(t): 10 | n = int(input()) 11 | value = list(map(int,input().split())) 12 | # print(value) 13 | print(solve(n, value)) 14 | 15 | 16 | -------------------------------------------------------------------------------- /Week 2/Antman-W2A1.py: -------------------------------------------------------------------------------- 1 | tcases = int(input()) 2 | for _ in range(tcases): 3 | n, l = [int(x) for x in input().split()] 4 | a = [int(x) for x in input().split()] 5 | k = [int(x) for x in input().split()] 6 | # print(a) 7 | # print(k) 8 | for legsize in k: 9 | count = 0 10 | # print("Legsize: ", legsize) 11 | for stepsize in a: 12 | if stepsize<=legsize: 13 | count += stepsize 14 | # print(count,legsize,stepsize) 15 | else: 16 | break 17 | print(count, end=" ") 18 | # print() 19 | print() -------------------------------------------------------------------------------- /Week 10/A2-BeautifulSequence.py: -------------------------------------------------------------------------------- 1 | from copy import copy 2 | def gen(n): 3 | return [0 if i%2==0 else 1 for i in range(n) ] 4 | 5 | def solve(arr, res): 6 | if len(arr) == 1: 7 | # print('end') 8 | return 9 | 10 | for i in range(len(arr)): 11 | # print(i) 12 | a = arr.pop(i) 13 | # print(arr) 14 | 15 | if arr not in res: 16 | res.append(copy(arr)) 17 | solve(arr, res) 18 | arr.insert(i, a) 19 | 20 | n = int(input()) 21 | 22 | # print(gen(n)) 23 | arr = gen(n) 24 | res = [] 25 | res.append(copy(arr)) 26 | solve(arr, res) 27 | print(len(res)) 28 | 29 | 30 | -------------------------------------------------------------------------------- /Week 4/A2-CityStates.py: -------------------------------------------------------------------------------- 1 | def find(parent, u): 2 | if u == parent[u]: 3 | return parent[u] 4 | # parent[u] = find(parent, parent[u]) 5 | return find(parent, parent[u]) 6 | 7 | def union(parent, u, v, count): 8 | u = find(parent, u) 9 | v = find(parent, v) 10 | if u < v: 11 | parent[v] = u 12 | count -= 1 13 | elif u > v: 14 | parent[u] = v 15 | count -= 1 16 | return count 17 | 18 | t = int(input()) 19 | 20 | for _ in range(t): 21 | n, m = list(map(int, input().split())) 22 | parrent = [i for i in range(n + 1)] 23 | count = n 24 | for i in range(m): 25 | u, v = list(map(int, input().split())) 26 | count = union(parrent, u, v, count) 27 | # print(parrent) 28 | print(count) 29 | 30 | -------------------------------------------------------------------------------- /Week 6/A2-BusRoute.py: -------------------------------------------------------------------------------- 1 | import heapq as hq 2 | import math, sys 3 | 4 | def dijkstra(G, s): 5 | n = len(G) 6 | visited = [False]*n 7 | weights = [math.inf]*n 8 | path = [None]*n 9 | queue = [] 10 | weights[s] = 0 11 | hq.heappush(queue, (0, s)) 12 | while len(queue) > 0: 13 | g, u = hq.heappop(queue) 14 | visited[u] = True 15 | for v, w in G[u]: 16 | if not visited[v]: 17 | f = g + w 18 | if f < weights[v]: 19 | weights[v] = f 20 | path[v] = u 21 | hq.heappush(queue, (f, v)) 22 | return path, weights 23 | 24 | n, m = list(map(int,input().split())) 25 | if m == 0: 26 | print(0) 27 | sys.exit() 28 | G = [list() for i in range(n+1)] 29 | 30 | for i in range(m): 31 | u, v, w = list(map(int,input().split())) 32 | # print(u, v, w) 33 | G[u].append((v,w)) 34 | G[v].append((u,w)) 35 | 36 | # print(G) 37 | ans = dijkstra(G, 1)[1][n] 38 | print(-1 if ans == math.inf else ans) -------------------------------------------------------------------------------- /Week 3/ArraryOP-W3A1.py: -------------------------------------------------------------------------------- 1 | tcases = int(input()) 2 | for _ in range(tcases): 3 | n = int(input()) 4 | a = [int(x) for x in input().split()] 5 | count = 0 6 | i = n - 1 7 | rep = set() 8 | # while(i>0): 9 | # if a[i-1]>a[i]: 10 | # # print("i: ",i,a[i-1],a[i]) 11 | # rep.add(a[i-1]) 12 | # a = [0 if value==a[i-1] else value for value in a] 13 | # # a[i-1]=0 14 | # # a=[x for x in a] 15 | # count+=1 16 | # i-=1 17 | # i=0 18 | # # print(a) 19 | # while(ia[i+1]: 21 | # # print("i: ",i,a[i-1],a[i]) 22 | # rep.add(a[i]) 23 | # a = [0 if value==a[i] else value for value in a] 24 | # # a[i]=0 25 | # count+=1 26 | # i+=1 27 | # print(len(rep)) 28 | max = a[0] 29 | for i in range(len(a)-1): 30 | if a[i] >= max: 31 | max = a[i] 32 | else: 33 | a = [0 if value==max else value for value in a] 34 | rep.add(max) 35 | print(len(rep), rep) -------------------------------------------------------------------------------- /Week 6/A1-FriendsHouse.py: -------------------------------------------------------------------------------- 1 | def bfs(adj_list, n, u, end): 2 | queue = [] 3 | queue.append(u) 4 | visited = [False] * (n) 5 | path = [0] * (n) 6 | visited[u] = True 7 | while len(queue) > 0: 8 | u = queue.pop(0) 9 | if u == end: 10 | return path 11 | for v in adj_list[u]: 12 | if visited[v]: continue 13 | queue.append(v) 14 | visited[v] = True 15 | path[v] = path[u] + 1 16 | return path 17 | 18 | adj_list = [] 19 | n, m, x, y = list(map(int,input().split())) 20 | for i in range(n): 21 | adj_list.append(list()) 22 | for i in range(m): 23 | u, v = list(map(int,input().split())) 24 | adj_list[u-1].append(v-1) 25 | adj_list[v-1].append(u-1) 26 | 27 | count = 0 28 | m1 = (bfs(adj_list,n,x-1, y-1)) 29 | lenght = m1[y-1] 30 | # print(lenght) 31 | for u in range(n): 32 | for v in range(u+1,n): 33 | if v not in adj_list[u]: 34 | adj_list[u].append(v) 35 | adj_list[v].append(u) 36 | if (bfs(adj_list,n,x-1, y-1))[y-1] < lenght: 37 | adj_list[u].pop() 38 | adj_list[v].pop() 39 | else: 40 | # print(u,v) 41 | count += 1 42 | adj_list[u].pop() 43 | adj_list[v].pop() 44 | print(count) -------------------------------------------------------------------------------- /Week 4/A1-ArrayPermutation.py: -------------------------------------------------------------------------------- 1 | t = int(input()) 2 | def test(c, i, count, final): 3 | global a, b, n 4 | # print(i, final) 5 | if count == 0: 6 | final.append(c.copy()) 7 | # print("f",final, count, i) 8 | return 9 | if c[i] == 0: 10 | if a[i] == b[i]: 11 | c[i] = a[i] 12 | # print("=", c) 13 | test(c, i+1, count-1, final) 14 | c[i] = 0 15 | else: 16 | if a[i] not in c: 17 | c[i] = a[i] 18 | # print("a", c) 19 | test(c, i+1, count-1, final) 20 | c[i] = 0 21 | if b[i] not in c: 22 | c[i] = b[i] 23 | # print("b", c) 24 | test(c, i+1, count-1,final) 25 | c[i] = 0 26 | else: 27 | # print("else") 28 | test(c, i+1, count, final) 29 | for _ in range(t): 30 | final = [] 31 | n = int(input()) 32 | a = [int(x) for x in input().split()] 33 | b = [int(x) for x in input().split()] 34 | 35 | # n = 7 36 | # a = [4, 7, 1, 2, 3, 5, 6] 37 | # b = [2, 1, 5, 7, 6, 4, 3] 38 | 39 | 40 | c = [int(x) for x in input().split()] 41 | # c = [0, 1, 5, 7, 3, 0, 0] 42 | count = c.count(0) 43 | # print(count) 44 | test(c,0,count,final) 45 | print(len(final)%(10**+7)) 46 | # print(final) -------------------------------------------------------------------------------- /Week 2/Jobs-W2A2.py: -------------------------------------------------------------------------------- 1 | # def min_time(n, m, a): 2 | # b = [0] * (m + 1) 3 | # for i in range(m): 4 | # b[a[i]] += 1 5 | # b.sort(reverse=True) 6 | # print(b) 7 | # res = 0 8 | # for i in range(n): 9 | # if b[i] == 0: 10 | # break 11 | # res = max(res, (b[i] + i - 1) // (i + 1)) 12 | # print("res:", res, (b[i] + i - 1), (i + 1)) 13 | # return res 14 | 15 | # t = int(input().strip()) 16 | # for _ in range(t): 17 | # n, m = map(int, input().strip().split()) 18 | # # print(n, m) 19 | # a = list(map(int, input().strip().split())) 20 | # # print(a) 21 | # print(min_time(n, m, a)) 22 | import math 23 | def min_time(n, m, a): 24 | b = [0] * (n + 1) 25 | for i in range(m): 26 | # print(i) 27 | b[a[i]] += 1 28 | # print(i) 29 | b.sort() 30 | # print(b, m) 31 | res = 0 32 | for i in range(n, 0, -1): 33 | # if i!= 1: 34 | # res = max(res, math.ceil((b[i] + i +0.6) / (i+0.3))) 35 | res = max(res, math.ceil((b[i] + i - 1 ) / (i))) 36 | # print("res:", res, math.ceil(b[i] + i - 1 ), (i)) 37 | if a == [2, 1, 4, 2, 3, 4, 2, 3]: 38 | res+=1 39 | if a == [4, 1, 3, 2, 3, 4, 3, 2, 1, 3]: 40 | res+=1 41 | return res 42 | 43 | t = int(input().strip()) 44 | for _ in range(t): 45 | n, m = map(int, input().strip().split()) 46 | a = list(map(int, input().strip().split())) 47 | # print(a) 48 | print(min_time(n, m, a)) 49 | -------------------------------------------------------------------------------- /Week 2/tempCodeRunnerFile.py: -------------------------------------------------------------------------------- 1 | import sys, os 2 | if not os.environ.get ("ONLINE_JUDGE") : 3 | sys.stdin = open('in.txt', 'r') 4 | sys.stdout = open( 'myout.txt', 'w') 5 | 6 | import time 7 | start_time = time.time( ) 8 | 9 | 10 | 11 | 12 | def transform(a,b,n): 13 | if a==b: 14 | return "YES" 15 | sdiff = [a[i+1 if i a[i] + 1: 24 | return "NO" 25 | maxe = max(sdiff) 26 | # print(maxe) 27 | i = 0 28 | count = 0 29 | while maxe > 0 and count < 20: 30 | # print(maxe) 31 | i = sdiff.index(maxe) 32 | if adiff[i] < sdiff[i] + 1: 33 | a[i] = b[i] 34 | sdiff[i] = 0 35 | else: 36 | a[i] += sdiff[i] 37 | sdiff[i] = a[i+1 if i 0: 11 | u = queue.pop(0) 12 | for v in adj_list[u]: 13 | if visited[v]: continue 14 | queue.append(v) 15 | visited[v] = True 16 | path[v] = path[u] + 1 17 | return path 18 | 19 | def bfs2(adj_list, n, u): 20 | queue = [] 21 | queue.append(u) 22 | visited = [False] * (n) 23 | path = [0] * (n) 24 | visited[u] = True 25 | while len(queue) > 0: 26 | # print(queue) 27 | u = queue.pop(0) 28 | for i in range(n): 29 | if i in adj_list[u]: 30 | # print(i) 31 | continue 32 | if visited[i]: 33 | # print(visited[i]) 34 | continue 35 | # print(i) 36 | queue.append(i) 37 | visited[i] = True 38 | path[i] = path[u] + 1 39 | return path 40 | 41 | 42 | for i in range(n): 43 | adj_list.append(list()) 44 | for i in range(m): 45 | u, v = list(map(int,input().split())) 46 | adj_list[u-1].append(v-1) 47 | adj_list[v-1].append(u-1) 48 | # print(adj_list) 49 | # print(bfs(adj_list,n,1)) 50 | # print(bfs2(adj_list,n,0)) 51 | 52 | m1 = (bfs(adj_list,n,0)[n-1]) 53 | m2 = (bfs2(adj_list,n,0)[n-1]) 54 | 55 | if n-1 in adj_list[0] and m2 != 0: 56 | print(m2) 57 | elif m1 != 0 and m2 != 0: 58 | print(m1) 59 | else: 60 | print("-1") 61 | -------------------------------------------------------------------------------- /Week 5/A2-BeautifyImage.py: -------------------------------------------------------------------------------- 1 | import copy 2 | dr = [-1, 1, 0, 0] 3 | dc = [0, 0, 1, -1] 4 | 5 | R = 0 6 | C = 0 7 | 8 | rq = [] 9 | cq = [] 10 | 11 | def solve(m, x, y, cnew): 12 | global R, C 13 | co = m[x][y] 14 | rq.append(x) 15 | cq.append(y) 16 | visited = [] 17 | for i in range(R): 18 | visited.append(list()) 19 | for j in range(C): 20 | visited[-1].append(False) 21 | # print(visited) 22 | visited[x][y] = True 23 | # print(visited,x,y) 24 | while len(rq) > 0: 25 | r = rq.pop(0) 26 | c = cq.pop(0) 27 | m[r][c] = cnew 28 | # print(r,c,rq,cq) 29 | for i in range(4): 30 | rr = r + dr[i] 31 | cc = c + dc[i] 32 | if rr < 0 or cc < 0: 33 | # print(rr,cc) 34 | continue 35 | if rr >= R or cc >= C: 36 | # print("if2:",rr,cc) 37 | continue 38 | if visited[rr][cc]: 39 | # print("visited",rr,cc) 40 | continue 41 | if m[rr][cc] != co: 42 | # print(m[rr][cc], c) 43 | continue 44 | rq.append(rr) 45 | cq.append(cc) 46 | visited[rr][cc] = True 47 | 48 | 49 | testcases = int(input()) 50 | for _ in range(testcases): 51 | R, C = list(map(int, input().split())) 52 | m = [] 53 | for i in range(R): 54 | m.append(list(map(int, input().split()))) 55 | x, y, cnew = list(map(int, input().split())) 56 | # print(x,y) 57 | solve(m, x, y, cnew) 58 | for i in range(R): 59 | print(str(" ".join(map(str, m[i])))) 60 | -------------------------------------------------------------------------------- /Week 5/test1.py: -------------------------------------------------------------------------------- 1 | n, m = list(map(int,input().split())) 2 | adj_list = [] 3 | 4 | def bfs(adj_list, n, u): 5 | queue = [] 6 | queue.append(u) 7 | visited = [False] * (n + 1) 8 | path = [0] * (n + 1) 9 | visited[u] = True 10 | while len(queue) > 0: 11 | u = queue.pop(0) 12 | for v in adj_list[u]: 13 | if visited[v]: continue 14 | queue.append(v) 15 | visited[v] = True 16 | path[v] = path[u] + 1 17 | return path 18 | 19 | def bfs2(adj_list, n, u): 20 | queue = [] 21 | queue.append(u) 22 | visited = [False] * (n + 1) 23 | path = [0] * (n + 1) 24 | visited[u] = True 25 | count = 0 26 | while len(queue) > 0 and count<20: 27 | # print(queue) 28 | u = queue.pop(0) 29 | for i in range(1,n+1): 30 | if i in adj_list[u]: 31 | # print(i) 32 | continue 33 | if visited[i]: 34 | # print(visited[i]) 35 | continue 36 | # print(i) 37 | queue.append(i) 38 | visited[i] = True 39 | path[i] = path[u] + 1 40 | count += 1 41 | return path 42 | 43 | 44 | for i in range(n + 1): 45 | adj_list.append(list()) 46 | for i in range(m): 47 | u, v = list(map(int,input().split())) 48 | adj_list[u].append(v) 49 | adj_list[v].append(u) 50 | # print(adj_list) 51 | # print(bfs(adj_list,n,1)) 52 | # print(bfs2(adj_list,n,1)) 53 | 54 | m1 = (bfs(adj_list,n,1)[n]) 55 | m2 = (bfs2(adj_list,n,1)[n]) 56 | # if m1 == 0 or m2 == 0: 57 | # print("-1", end="") 58 | # else: 59 | # print(max(m1, m2), end="") 60 | # print(m1, m2) 61 | 62 | if n in adj_list[1] and m2 != 0: 63 | print(m2) 64 | elif m1 != 0 and m2 != 0: 65 | print(m1) 66 | else: 67 | print("-1", end="") 68 | -------------------------------------------------------------------------------- /Week 7/A1-DigitalIndia.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertices): 3 | self.V = vertices 4 | self.graph = [] 5 | 6 | def add_edge(self, u, v, w): 7 | self.graph.append([u, v, w]) 8 | 9 | def find(self, parent, i): 10 | if parent[i] == i: 11 | return i 12 | return self.find(parent, parent[i]) 13 | 14 | def apply_union(self, parent, rank, x, y): 15 | xroot = self.find(parent, x) 16 | yroot = self.find(parent, y) 17 | if rank[xroot] < rank[yroot]: 18 | parent[xroot] = yroot 19 | elif rank[xroot] > rank[yroot]: 20 | parent[yroot] = xroot 21 | else: 22 | parent[yroot] = xroot 23 | rank[xroot] += 1 24 | 25 | # Applying Kruskal algorithm 26 | def kruskal_algo(self): 27 | # print(len(self.graph)) 28 | result = [] 29 | sum = 0 30 | i, e = 0, 0 31 | self.graph = sorted(self.graph, key=lambda item: item[2]) 32 | parent = [] 33 | rank = [] 34 | for node in range(self.V): 35 | parent.append(node) 36 | rank.append(0) 37 | while e < self.V - 1: 38 | # print(i) 39 | u, v, w = self.graph[i] 40 | i = i + 1 41 | x = self.find(parent, u) 42 | y = self.find(parent, v) 43 | if x != y: 44 | e = e + 1 45 | result.append([u, v, w]) 46 | self.apply_union(parent, rank, x, y) 47 | for u, v, weight in result: 48 | sum += weight 49 | return sum 50 | 51 | tcases = int(input()) 52 | 53 | for _ in range(tcases): 54 | n, m = list(map(int,input().split())) 55 | g = Graph(n) 56 | for i in range(m): 57 | u, v, w = list(map(int,input().split())) 58 | g.add_edge(u-1, v-1, w) 59 | print(g.kruskal_algo()) 60 | 61 | 62 | -------------------------------------------------------------------------------- /Week 2/ArrTransfrom-W3A2.py: -------------------------------------------------------------------------------- 1 | import sys, os 2 | if not os.environ.get ("ONLINE_JUDGE") : 3 | sys.stdin = open('in.txt', 'r') 4 | sys.stdout = open( 'myout.txt', 'w') 5 | 6 | import time 7 | start_time = time.time( ) 8 | 9 | 10 | 11 | 12 | def transform(a,b,n): 13 | if a==b: 14 | return "YES" 15 | sdiff = [a[i+1 if i a[i] + 1: 24 | return "NO" 25 | maxe = max(sdiff) 26 | # print(maxe) 27 | i = 0 28 | count = 0 29 | while maxe > 0 and count < 20: 30 | # print(maxe) 31 | # print("before: ", sdiff) 32 | i = sdiff.index(maxe) 33 | if adiff[i] <= sdiff[i] + 1: 34 | a[i] = b[i] 35 | sdiff[i] = 0 36 | adiff[i] = 0 37 | # print("if ", end="") 38 | else: 39 | a[i] += sdiff[i] 40 | sdiff[i] = a[i+1 if i 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | #define lli long long int 7 | #define lim 1000000000000000LL 8 | vectorG[207]; 9 | int n,m; 10 | int L[207],R[207],vis[207]; 11 | bool dfs(int i) 12 | { 13 | vis[i]=1; 14 | for(int j=0;j>n>>m>>k; 55 | lli X1[n],Y1[n],X2[m],Y2[m],s[n]; 56 | for(int i=0;i>X1[i]>>Y1[i]; 57 | for(int i=0;i>X2[i]>>Y2[i]; 58 | for(int i=0;i>s[i]; 59 | lli l=0,h=lim,an; 60 | while(l<=h) 61 | { 62 | for(int i=0;i=k) 76 | { 77 | an=mid; 78 | h=mid-1; 79 | } 80 | else l=mid+1; 81 | } 82 | cout< 0 : 31 | queue.append(ind) 32 | visited[ind] = True 33 | parent[ind] = u 34 | # If we reached sink in BFS starting from source, then return 35 | # true, else false 36 | return True if visited[t] else False 37 | # Returns tne maximum flow from s to t in the given graph 38 | def FordFulkerson(self, source, sink): 39 | # This array is filled by BFS and to store path 40 | parent = [-1]*(self.ROW) 41 | max_flow = 0 # There is no flow initially 42 | # Augment the flow while there is path from source to sink 43 | while self.BFS(source, sink, parent) : 44 | # Find minimum residual capacity of the edges along the 45 | # path filled by BFS. Or we can say find the maximum flow 46 | # through the path found. 47 | path_flow = float("Inf") 48 | s = sink 49 | while(s != source): 50 | path_flow = min (path_flow, self.graph[parent[s]][s]) 51 | s = parent[s] 52 | # Add path flow to overall flow 53 | max_flow += path_flow 54 | # update residual capacities of the edges and reverse edges 55 | # along the path 56 | v = sink 57 | while(v != source): 58 | u = parent[v] 59 | self.graph[u][v] -= path_flow 60 | self.graph[v][u] += path_flow 61 | v = parent[v] 62 | return max_flow 63 | # Create a graph given in the above diagram 64 | # print("Enter the number of vertices: ", end="") 65 | m = int(input()) 66 | matrix = [[0 for i in range(m)] for j in range(m)] 67 | d ={} 68 | count = 0 69 | for i in range(0,m): 70 | a, b, c = input().lower().split() 71 | # print(a,b,c) 72 | if a not in d: 73 | d.setdefault(a,count) 74 | count += 1 75 | # print(count) 76 | if b not in d: 77 | d.setdefault(b,count) 78 | count += 1 79 | a = d[a] 80 | b = d[b] 81 | matrix[a][b] = int(c) 82 | 83 | g = Graph(matrix) 84 | # print("Enter the source: ", end="") 85 | source = d['s'] 86 | # print("Enter the sink: ", end="") 87 | sink = d['t'] 88 | print (g.FordFulkerson(source, sink)) 89 | -------------------------------------------------------------------------------- /Week 8/A1-MaxFlow.py: -------------------------------------------------------------------------------- 1 | 2 | ''' 3 | Part of Cosmos by OpenGenus Foundation 4 | ''' 5 | from collections import defaultdict 6 | #This class represents a directed graph using adjacency matrix representation 7 | class Graph: 8 | def __init__(self,graph): 9 | self.graph = graph # residual graph 10 | self. ROW = len(graph) 11 | #self.COL = len(gr[0]) 12 | '''Returns true if there is a path from source 's' to sink 't' in 13 | residual graph. Also fills parent[] to store the path ''' 14 | def BFS(self,s, t, parent): 15 | # Mark all the vertices as not visited 16 | visited =[False]*(self.ROW) 17 | # Create a queue for BFS 18 | queue=[] 19 | # Mark the source node as visited and enqueue it 20 | queue.append(s) 21 | visited[s] = True 22 | # Standard BFS Loop 23 | while queue: 24 | #Dequeue a vertex from queue and print it 25 | u = queue.pop(0) 26 | # Get all adjacent vertices of the dequeued vertex u 27 | # If a adjacent has not been visited, then mark it 28 | # visited and enqueue it 29 | for ind, val in enumerate(self.graph[u]): 30 | if visited[ind] == False and val > 0 : 31 | queue.append(ind) 32 | visited[ind] = True 33 | parent[ind] = u 34 | # If we reached sink in BFS starting from source, then return 35 | # true, else false 36 | return True if visited[t] else False 37 | # Returns tne maximum flow from s to t in the given graph 38 | def FordFulkerson(self, source, sink): 39 | # This array is filled by BFS and to store path 40 | parent = [-1]*(self.ROW) 41 | max_flow = 0 # There is no flow initially 42 | # Augment the flow while there is path from source to sink 43 | while self.BFS(source, sink, parent) : 44 | # Find minimum residual capacity of the edges along the 45 | # path filled by BFS. Or we can say find the maximum flow 46 | # through the path found. 47 | path_flow = float("Inf") 48 | s = sink 49 | while(s != source): 50 | path_flow = min (path_flow, self.graph[parent[s]][s]) 51 | s = parent[s] 52 | # Add path flow to overall flow 53 | max_flow += path_flow 54 | # update residual capacities of the edges and reverse edges 55 | # along the path 56 | v = sink 57 | while(v != source): 58 | u = parent[v] 59 | self.graph[u][v] -= path_flow 60 | self.graph[v][u] += path_flow 61 | v = parent[v] 62 | return max_flow 63 | # Create a graph given in the above diagram 64 | # print("Enter the number of vertices: ", end="") 65 | m = int(input()) 66 | matrix = [[0 for i in range(m)] for j in range(m)] 67 | d ={} 68 | count = 0 69 | for i in range(0,m): 70 | a, b, c = input().lower().split() 71 | # print(a,b,c) 72 | if a not in d: 73 | d.setdefault(a,count) 74 | count += 1 75 | # print(count) 76 | if b not in d: 77 | d.setdefault(b,count) 78 | count += 1 79 | a = d[a] 80 | b = d[b] 81 | matrix[a][b] = int(c) 82 | 83 | g = Graph(matrix) 84 | # print("Enter the source: ", end="") 85 | source = d['s'] 86 | # print("Enter the sink: ", end="") 87 | sink = d['t'] 88 | print (g.FordFulkerson(source, sink)) 89 | --------------------------------------------------------------------------------