smj007

Best Sci score

Aug 23rd, 2025
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. from collections import defaultdict
  2.  
  3. def max_sci_score(travel, point):
  4.  
  5.     # build reward map
  6.     reward = {p[0]: int(p[1]) for p in point}
  7.  
  8.     # build graph
  9.     graph = defaultdict(list)
  10.     for src, cost, dest in travel:
  11.         graph[src].append([dest, int(cost)])
  12.  
  13.     # memoization
  14.     memo = {}
  15.  
  16.     # perform dfs
  17.     def dfs(node):
  18.         """max score: reward - cost"""
  19.         # base case: end point - no outward going node
  20.         if node not in graph:
  21.             return reward.get(node, 0)
  22.         # use memoization
  23.         if node in memo:
  24.             return memo[node]
  25.  
  26.         best = -float("inf")
  27.  
  28.         for nbr, cost in graph[node]:
  29.             candidate = dfs(nbr) - cost
  30.             best = max(candidate, best)
  31.  
  32.         memo[node] = reward.get(node, 0) + best
  33.         return memo[node]
  34.  
  35.     return dfs("start")
  36.  
  37. travel = [["start","3","A"], ["A","4","B"], ["B","5","END1"]]
  38. point  = [["A","5"], ["B","6"], ["END1","3"]]
  39. print(max_sci_score(travel, point))
Advertisement
Add Comment
Please, Sign In to add comment