Skip to content

Commit e79642c

Browse files
authored
Update maximum-cost-of-trip-with-k-highways.py
1 parent 9113ca4 commit e79642c

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

Python/maximum-cost-of-trip-with-k-highways.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66

77
# combination based dp
8-
class Solution2(object):
8+
class Solution(object):
99
def maximumCost(self, n, highways, k):
1010
"""
1111
:type n: int
@@ -19,24 +19,25 @@ def maximumCost(self, n, highways, k):
1919
for c1, c2, t in highways:
2020
adj[c1].append((c2, t))
2121
adj[c2].append((c1, t))
22+
result = -1 if k != 1 else 0
2223
dp = [[0, []] for _ in xrange((1<<n))]
2324
for i in xrange(n):
2425
dp[1<<i][1].append(i)
25-
result = -1
2626
for cnt in xrange(1, n+1):
2727
for choice in itertools.combinations(xrange(n), cnt):
2828
mask = reduce(lambda x, y:x|(1<<y), choice, 0)
29-
for u in dp[mask][1]:
29+
total, lasts = dp[mask]
30+
for u in lasts:
3031
for v, t in adj[u]:
3132
if mask&(1<<v):
3233
continue
3334
new_mask = mask|(1<<v)
34-
if dp[mask][0]+t < dp[new_mask][0]:
35+
if total+t < dp[new_mask][0]:
3536
continue
36-
if dp[mask][0]+t == dp[new_mask][0]:
37+
if total+t == dp[new_mask][0]:
3738
dp[new_mask][1].append(v)
3839
continue
39-
dp[new_mask][0] = dp[mask][0]+t
40+
dp[new_mask][0] = total+t
4041
dp[new_mask][1] = [v]
4142
if bin(mask).count('1') == k:
4243
result = max(result, dp[new_mask][0])

0 commit comments

Comments
 (0)