|
| 1 | +from collections import defaultdict |
| 2 | +from typing import List |
| 3 | + |
| 4 | + |
| 5 | +class Solution: |
| 6 | + def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: |
| 7 | + graph = defaultdict(list) |
| 8 | + for u, v in edges: |
| 9 | + graph[u].append(v) |
| 10 | + graph[v].append(u) |
| 11 | + |
| 12 | + def dfs_bob(node: int) -> List[int]: |
| 13 | + if node == 0: |
| 14 | + return [node] |
| 15 | + nonlocal visited |
| 16 | + visited.add(node) |
| 17 | + path = [] |
| 18 | + for neighbour in graph[node]: |
| 19 | + if neighbour not in visited: |
| 20 | + path = dfs_bob(neighbour) |
| 21 | + if path: |
| 22 | + return [node] + path |
| 23 | + visited = set() |
| 24 | + bob_path = dfs_bob(bob) |
| 25 | + bob_visited_times = {node: i for i, node in enumerate(bob_path)} |
| 26 | + |
| 27 | + def dfs_alice(node: int, time: int) -> int: |
| 28 | + max_amount = float('-inf') |
| 29 | + nonlocal visited |
| 30 | + visited.add(node) |
| 31 | + for neighbour in graph[node]: |
| 32 | + if neighbour not in visited: |
| 33 | + max_amount = max(max_amount, dfs_alice(neighbour, time+1)) |
| 34 | + vertex_income = amount[node] |
| 35 | + if bob_visited_times.get(node, float('inf')) < time: |
| 36 | + vertex_income = 0 |
| 37 | + elif bob_visited_times.get(node, float('inf')) == time: |
| 38 | + vertex_income = amount[node] // 2 |
| 39 | + if max_amount == float('-inf'): |
| 40 | + return vertex_income |
| 41 | + return max_amount + vertex_income |
| 42 | + |
| 43 | + visited = set() |
| 44 | + return dfs_alice(0, 0) |
| 45 | + |
| 46 | + |
| 47 | +def main(): |
| 48 | + edges = [[0, 1], [1, 2], [1, 3], [3, 4]] |
| 49 | + bob = 3 |
| 50 | + amount = [-2, 4, 2, -4, 6] |
| 51 | + assert Solution().mostProfitablePath(edges, bob, amount) == 6 |
| 52 | + |
| 53 | + edges = [[0, 1]] |
| 54 | + bob = 1 |
| 55 | + amount = [-7280, 2350] |
| 56 | + assert Solution().mostProfitablePath(edges, bob, amount) == -7280 |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + main() |
0 commit comments