Lv.4bitmaskdp
Traveling Salesman (Bitmask DP)
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
cost[i][j] is the (possibly asymmetric) cost from city i to city j. Starting at city 0, visit every other city exactly once
and return to 0; return the minimum total cost.
Examples
| cost | result |
|---|---|
[[0, 10, 15, 20], [5, 0, 9, 10], [6, 13, 0, 12], [8, 8, 9, 0]] | 35 |
[[0, 3], [7, 0]] | 10 |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(cost: int[][]) → int
Constraints
- ;
cost[i][i] = 0, otherwisecost[i][j]
Expected complexity
- Time
- O(2^N * N^2)
- Space
- O(2^N * N)
Examples
| cost | Expected |
|---|---|
[[0,10,15,20],[5,0,9,10],[6,13,0,12],[8,8,9,0]] | 35 |
[[0,3],[7,0]] | 10 |
Hint
Hint
Bitmask DP over (visited set, current city): dp[1][0] = 0, extend to unvisited w, answer
min dp[full][v] + cost[v][0]; . Trying all orders exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1000 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 2 | inputs and outputs |
| correctness | 40 | 7 | verdict only |
| performance | 60 | 4 | verdict only |