Skip to content

Commit 9113ca4

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

File tree

1 file changed

+31
-31
lines changed

1 file changed

+31
-31
lines changed

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

Lines changed: 31 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,6 @@
11
# Time: O(n^2 * 2^n)
22
# Space: O(n * 2^n)
33

4-
# bfs based dp
5-
class Solution(object):
6-
def maximumCost(self, n, highways, k):
7-
"""
8-
:type n: int
9-
:type highways: List[List[int]]
10-
:type k: int
11-
:rtype: int
12-
"""
13-
if k+1 > n: # required to optimize, otherwise, TLE or MLE
14-
return -1
15-
adj = [[] for _ in xrange(n)]
16-
for c1, c2, t in highways:
17-
adj[c1].append((c2, t))
18-
adj[c2].append((c1, t))
19-
result = -1
20-
dp = [(u, 1<<u, 0) for u in xrange(n)]
21-
while dp:
22-
new_dp = []
23-
for u, mask, total in dp:
24-
if bin(mask).count('1') == k+1:
25-
result = max(result, total)
26-
for v, t in adj[u]:
27-
if mask&(1<<v) == 0:
28-
new_dp.append((v, mask|(1<<v), total+t))
29-
dp = new_dp
30-
return result
31-
32-
33-
# Time: O(n^2 * 2^n)
34-
# Space: O(n * 2^n)
354
import itertools
365

376

@@ -72,3 +41,34 @@ def maximumCost(self, n, highways, k):
7241
if bin(mask).count('1') == k:
7342
result = max(result, dp[new_mask][0])
7443
return result
44+
45+
46+
# Time: O(n^2 * 2^n)
47+
# Space: O(n * 2^n)
48+
# bfs based dp
49+
class Solution2(object):
50+
def maximumCost(self, n, highways, k):
51+
"""
52+
:type n: int
53+
:type highways: List[List[int]]
54+
:type k: int
55+
:rtype: int
56+
"""
57+
if k+1 > n: # required to optimize, otherwise, TLE or MLE
58+
return -1
59+
adj = [[] for _ in xrange(n)]
60+
for c1, c2, t in highways:
61+
adj[c1].append((c2, t))
62+
adj[c2].append((c1, t))
63+
result = -1
64+
dp = [(u, 1<<u, 0) for u in xrange(n)]
65+
while dp:
66+
new_dp = []
67+
for u, mask, total in dp:
68+
if bin(mask).count('1') == k+1:
69+
result = max(result, total)
70+
for v, t in adj[u]:
71+
if mask&(1<<v) == 0:
72+
new_dp.append((v, mask|(1<<v), total+t))
73+
dp = new_dp
74+
return result

0 commit comments

Comments
 (0)