From f7f9c08df8ab8d8defde417b74ffdb5781e0aa32 Mon Sep 17 00:00:00 2001 From: Daniel <59575049+lemoentjiez@users.noreply.github.com> Date: Mon, 26 Dec 2022 15:32:12 +0200 Subject: [PATCH] Update courses.py --- LabMD_3/courses.py | 55 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/LabMD_3/courses.py b/LabMD_3/courses.py index 8b13789..27dd233 100644 --- a/LabMD_3/courses.py +++ b/LabMD_3/courses.py @@ -1 +1,56 @@ +from collections import defaultdict, deque +class Solution: + def solve(self, edges): + graph = defaultdict(list) + weights = {} + max_weight = 0 + N = 0 + for u, v, w in edges: + graph[u].append(v) + graph[v].append(u) + weights[u, v] = w + weights[v, u] = w + N = max(N, u + 1, v + 1) + max_weight = max(max_weight, w) + def bfs(root, weight_cap): + target = N - 1 + Q = deque([(root, 0, 0)]) + visited = [False] * N + visited[0] = True + while Q: + v, d, current_weight = Q.pop() + if v == N - 1: + return d, current_weight + for w in graph[v]: + if visited[w]: + continue + new_weight = weights[v, w] + if new_weight <= weight_cap: + visited[w] = True + Q.appendleft((w, d + 1, max(current_weight, new_weight))) + return -1, -1 + result = float("inf") + while max_weight >= 0: + d, weight = bfs(0, max_weight) + if d >= 0: + result = min(result, d * weight) + max_weight = weight - 1 + else: + break + return result if result < float("inf") else -1 + +ob = Solution() +graph = [ + [0, 1, 1], + [1, 2, 1], + [2, 3, 1], + [3, 4, 1] +] + +value = (ob.solve(graph)) + +if value == len(graph): + print("possible") +else: + print("impossible")