


class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
g = defaultdict(list)
for x, y in edges:
g[x].append(y)
g[y].append(x)
leaves = []
for node in g:
if len(g[node]) == 1 and node != 0:
leaves.append(node)
leaves = set(leaves)
leaves_bool = defaultdict(bool)
for leaf in leaves:
leaves_bool[leaf] = True
# 先看看bob到0怎么走
path = []
flag = False
def dfs1(cur, temp_path, fa):
nonlocal flag, path
if flag:
return
if cur == 0:
path = temp_path[:]
flag = True
return
for next in g[cur]:
if next != fa:
dfs1(next, temp_path + [next], cur)
dfs1(bob, [bob], -1)
bob_step = defaultdict(int)
bob_step_bool = defaultdict(bool)
for i, v in enumerate(path):
bob_step[v] = i
bob_step_bool[v] = True
ans = -inf
@cache
def dfs2(cur, temp_path, fa, cnt):
nonlocal ans
v = cur
if bob_step_bool[v] is False:
cnt += amount[v]
else:
if len(temp_path) - 1 == bob_step[v]:
cnt += amount[v] // 2
elif len(temp_path) - 1 > bob_step[v]:
cnt += 0
else:
cnt += amount[v]
if leaves_bool[cur] is True:
#print(cur, temp_path, fa, cnt)
ans = max(ans, cnt)
return
for next in g[cur]:
if next != fa:
dfs2(next, tuple(list(temp_path) + [next]), cur, cnt)
dfs2(0, tuple([0]), -1, 0)
return ans
class Solution:
def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int:
g = defaultdict(list)
for x, y in edges:
g[x].append(y)
g[y].append(x)
leaves = []
for node in g:
if len(g[node]) == 1 and node != 0:
leaves.append(node)
leaves = set(leaves)
leaves_bool = defaultdict(bool)
for leaf in leaves:
leaves_bool[leaf] = True
# 先看看bob到0怎么走
path = []
flag = False
temp_path = [bob]
def dfs1(cur, fa):
nonlocal flag, path
if flag:
return
if cur == 0:
path = temp_path[:]
flag = True
return
for next in g[cur]:
if next != fa:
temp_path.append(next)
dfs1(next, cur)
temp_path.pop()
dfs1(bob, -1)
bob_step = defaultdict(int)
bob_step_bool = defaultdict(bool)
for i, v in enumerate(path):
bob_step[v] = i
bob_step_bool[v] = True
ans = -inf
temp_path = [0]
cnt = 0
def dfs2(cur, fa):
nonlocal ans, cnt
cnt1 = cnt
v = cur
if bob_step_bool[v] is False:
cnt1 += amount[v]
else:
if len(temp_path) - 1 == bob_step[v]:
cnt1 += amount[v] // 2
elif len(temp_path) - 1 > bob_step[v]:
cnt1 += 0
else:
cnt1 += amount[v]
if leaves_bool[cur] is True:
#print(cur, temp_path, fa, cnt)
ans = max(ans, cnt1)
return
origin_cnt = cnt
for next in g[cur]:
if next != fa:
temp_path.append(next)
cnt = cnt1
dfs2(next, cur)
cnt = origin_cnt
temp_path.pop()
dfs2(0, -1)
return ans