Skip to content

Commit

Permalink
Merge pull request #4947 from CryoJS/patch5
Browse files Browse the repository at this point in the history
Python Sol for Hamiltonian Flights in DP Bitmasks Module
  • Loading branch information
SansPapyrus683 authored Dec 3, 2024
2 parents 29b5713 + 558fae4 commit e5fea5c
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions content/4_Gold/DP_Bitmasks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,55 @@ int main() {
```

</CPPSection>
<PySection>

<Warning>

Due to Python's large constant factor, the solution below TLEs.

</Warning>

```py
import sys

MOD = 10**9 + 7

input = sys.stdin.readline

n, m = map(int, input().strip().split())
dp = [[0 for _ in range(n)] for _ in range(1 << n)]
dp[1][0] = 1

adj = [[] for _ in range(n)]
for i in range(m):
a, b = map(int, input().strip().split())
adj[b - 1].append(a - 1)

for cities in range(1, 1 << n):
# only consider cities that include the first city
if not cities & 1:
continue

# only consider subsets with the last city if it's the full subset
if cities & (1 << n - 1) and cities != (1 << n) - 1:
continue

# loop through possible ending cities
for end in range(1, n):
if not cities & (1 << end):
continue

prev_cities = cities ^ (1 << end)
for prev_end in adj[end]:
if not prev_cities & (1 << prev_end):
continue
dp[cities][end] += dp[prev_cities][prev_end]
dp[cities][end] %= MOD

print(dp[(1 << n) - 1][n - 1])
```

</PySection>

</LanguageSection>

Expand Down

0 comments on commit e5fea5c

Please sign in to comment.