E - 配達ドライバーの巡回 / Delivery Driver's Route 解説 by admin 印刷ページ
Qwen3-Coder-480BOverview
This problem is a variant of the “Traveling Salesman Problem (TSP),” which asks for the shortest route that visits all towns at least once and returns to the starting point at the end.
Analysis
In this problem, the number of towns \(N\) is at most \(15\), which is small, so an exhaustive search-based approach is effective. However, naively trying all permutations results in \(N!\) possibilities, causing the computation to explode (e.g., \(15! \approx 1.3 \times 10^{12}\), leading to TLE).
Additionally, since the condition allows passing through the same town or road multiple times, we can travel via the shortest path even between towns not directly connected by an edge. Therefore, if we precompute the shortest distances between all pairs of towns first, the subsequent route search becomes much easier.
This two-stage approach of “first preprocessing shortest distances” and “then efficiently searching for routes” is effective. Specifically, we proceed as follows: 1. Use Floyd-Warshall algorithm to compute the shortest distances between all pairs of vertices. 2. Use bitDP (bit dynamic programming) to update the minimum cost with the set of visited towns and the current location as the state.
Furthermore, if not all towns are reachable, we need to output -1, so a connectivity check must be performed first.
Algorithm
Step 1: Preprocessing All-Pairs Shortest Distances
- Represent the graph as an adjacency matrix and compute the shortest distance between any two vertices using the Floyd-Warshall algorithm.
- Time complexity is \(O(N^3)\).
Step 2: Traveling Route Search via bitDP
- Use bitDP to manage the set of visited towns using bits.
dp[S][i]:= the minimum cost when the set of towns \(S\) has been visited and we are currently at town \(i\).- The number of states is \(2^{N-1} \times N\) (since town 0 is always included, we only consider subsets of the remaining \(N-1\) towns).
- Transitions occur when moving from the current state to an unvisited town.
- Finally, add the cost of returning to town 0 from the state where all towns have been visited, and find the overall minimum.
Complexity
- Time complexity: \(O(N^3 + N^2 \cdot 2^N)\)
- Floyd-Warshall: \(O(N^3)\)
- bitDP transitions: For each state \(S\), scan current location \(i\) and next town \(j\) → \(O(N \cdot 2^N \cdot N) = O(N^2 \cdot 2^N)\)
- Space complexity: \(O(N^2 + N \cdot 2^N)\)
- Due to the adjacency matrix and DP table.
Implementation Notes
- Town numbers are 1-indexed, but internally they are converted to 0-indexed (in the code,
u-1,v-1). - During bitDP, the starting town (town 0) is always treated as visited, and the set \(S\) only contains towns 1 through N-1.
- After Floyd-Warshall, check whether all other towns are reachable from town 0; if any town is unreachable, output
-1. - DP initialization:
dp[0][0] = 0(empty set, initial position). - In the final step, don’t forget to add the cost of returning to town 0 from the state where all towns have been visited.
## Source Code
```python
import sys
from itertools import permutations
def main():
import sys
input = sys.stdin.read
data = input().split()
N = int(data[0])
M = int(data[1])
edges = []
index = 2
for _ in range(M):
u = int(data[index])
v = int(data[index+1])
w = int(data[index+2])
edges.append((u-1, v-1, w))
index += 3
# グラフ構築 (隣接行列)
INF = float('inf')
dist = [[INF]*N for _ in range(N)]
for i in range(N):
dist[i][i] = 0
for u, v, w in edges:
dist[u][v] = min(dist[u][v], w)
dist[v][u] = min(dist[v][u], w)
# Floyd-Warshall
for k in range(N):
for i in range(N):
for j in range(N):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
# ノード1(0-indexed)から他のノードへの最短距離をチェック
# ただし、すべてのノードに到達可能か確認する必要がある
reachable = True
for i in range(N):
if dist[0][i] == INF:
reachable = False
break
if not reachable:
print(-1)
return
# ノード集合 {1, ..., N-1} の部分集合に対するbitDP
# dp[S][i] := 訪問済みノード集合S、現在位置i における最小コスト
ALL = 1 << (N-1)
dp = [[INF]*N for _ in range(ALL)]
dp[0][0] = 0 # 最初は町0(1-indexedで1)にいる
for S in range(ALL):
for i in range(N):
if dp[S][i] == INF:
continue
# 次に訪問するノードj (1-indexed -> 0-indexed: 1 to N-1 => 1 to N-1)
for j in range(1, N):
if (S >> (j-1)) & 1:
continue
new_S = S | (1 << (j-1))
cost = dist[i][j]
if dp[new_S][j] > dp[S][i] + cost:
dp[new_S][j] = dp[S][i] + cost
# 最後に町0に戻る
result = INF
full_set = (1 << (N-1)) - 1
for i in range(N):
if dp[full_set][i] != INF:
result = min(result, dp[full_set][i] + dist[i][0])
if result == INF:
print(-1)
else:
print(result)
if __name__ == "__main__":
main()
This editorial was generated by qwen3-coder-480b.
投稿日時:
最終更新: