公式

E - 配達ロボットの巡回 / Delivery Robot's Patrol 解説 by admin 印刷ページ

Claude 4.5 Opus

Overview

This is a problem of finding the shortest path that starts from a starting point on a grid, visits all package drop-off locations, and returns to the starting point. This is a classic Traveling Salesman Problem (TSP) and can be efficiently solved using bitmask DP.

Analysis

Key Observations

  1. No obstacles → When moving between two points on the grid, the shortest distance is always the Manhattan distance. The Manhattan distance is \(|x_1 - x_2| + |y_1 - y_2|\), which is the sum of the vertical and horizontal movement distances.

  2. Visiting order matters → The total travel distance changes depending on the order in which all package drop-off locations are visited. We need to find the optimal visiting order.

  3. Traveling Salesman Problem (TSP) → This is the well-known problem of finding the shortest path that visits all locations exactly once and returns to the start.

Issues with the Naive Approach

There are \(K!\) possible orderings to visit \(K\) package drop-off locations. When \(K = 15\), this becomes \(15! = 1,307,674,368,000\) orderings, which is far too many for brute-force search.

Solution: Bitmask DP

By managing “which package drop-off locations have been visited” as a bit string, we can drastically reduce the computation. For example, when \(K = 3\), the bit string 101 means “the 1st and 3rd package drop-off locations have been visited.”

Algorithm

Step 1: Precompute Distances

Compute the Manhattan distance between the starting point (labeled 0) and each package drop-off location (labeled 1 through K), for all pairs.

Step 2: Bitmask DP Definition

  • \(dp[mask][i]\) = the minimum number of steps when the set of visited locations is \(mask\) and the current position is \(i\)
  • \(mask\) is a \(K\)-bit integer, where if bit \(j\) is 1, then package drop-off location \(j+1\) has been visited

Step 3: Transitions

From the current state \((mask, cur)\), consider transitioning to an unvisited package drop-off location \(next\):

\[dp[mask | (1 << (next-1))][next] = \min(dp[mask | (1 << (next-1))][next], dp[mask][cur] + dist[cur][next])\]

Step 4: Computing the Answer

From the state where all package drop-off locations have been visited, \(full\_mask = 2^K - 1\), add the cost of returning to the starting point and find the minimum:

\[ans = \min_{last=1}^{K}(dp[full\_mask][last] + dist[last][0])\]

Concrete Example (K=2)

When the package drop-off locations are at \((2, 3)\) and \((4, 1)\): - State 00: No location visited (at the starting point) - State 01: Only the 1st location visited - State 10: Only the 2nd location visited - State 11: Both locations visited

For each state, we also record “where we currently are” and update the minimum cost accordingly.

Complexity

  • Time complexity: \(O(2^K \cdot K^2)\)
    • The number of states is \(O(2^K \cdot K)\), and each state has \(O(K)\) possible transitions
    • Since \(K \leq 15\), we have \(2^{15} \times 15^2 \approx 7.4 \times 10^6\), which is fast enough
  • Space complexity: \(O(2^K \cdot K)\)
    • The size of the DP table

Implementation Notes

  • Correspondence with 0-indexed: Managing the starting point as index 0 and the package drop-off locations as indices 1 through K makes bit operations easier to understand. Bit \(j\) corresponds to package drop-off location \(j+1\).

  • Special handling for K=0: If there are no package drop-off locations, no movement is needed, so output 0 immediately.

  • INF initialization: Initialize with a sufficiently large value (float('inf')) to represent unreachable states.

  • Grid size \(N, M\) is unnecessary: Since there are no obstacles, Manhattan distances can be computed from coordinates alone.

    Source Code

import sys
from functools import lru_cache

def main():
    input_data = sys.stdin.read().split()
    idx = 0
    N = int(input_data[idx]); idx += 1
    M = int(input_data[idx]); idx += 1
    K = int(input_data[idx]); idx += 1
    
    if K == 0:
        print(0)
        return
    
    # 荷物置き場の座標を読み込む
    places = [(1, 1)]  # 0番目はスタート地点
    for i in range(K):
        r = int(input_data[idx]); idx += 1
        c = int(input_data[idx]); idx += 1
        places.append((r, c))
    
    # 各地点間のマンハッタン距離を計算
    # グリッド上で障害物がないので、マンハッタン距離が最短距離
    num_places = K + 1  # スタート地点 + K個の荷物置き場
    dist = [[0] * num_places for _ in range(num_places)]
    
    for i in range(num_places):
        for j in range(num_places):
            dist[i][j] = abs(places[i][0] - places[j][0]) + abs(places[i][1] - places[j][1])
    
    # 巡回セールスマン問題をビットDPで解く
    # dp[mask][i] = 訪問済み集合がmask、現在地がiのときの最小移動歩数
    # maskのビットは荷物置き場1〜Kに対応(スタート地点は含まない)
    
    INF = float('inf')
    full_mask = (1 << K) - 1
    
    # dp[mask][i]: maskは訪問済みの荷物置き場のビット集合、iは現在位置(0〜K)
    dp = [[INF] * num_places for _ in range(1 << K)]
    
    # 初期状態: スタート地点(0)にいる、どの荷物置き場も訪問していない
    dp[0][0] = 0
    
    for mask in range(1 << K):
        for cur in range(num_places):
            if dp[mask][cur] == INF:
                continue
            
            # 次に訪問する荷物置き場を選ぶ
            for next_place in range(1, num_places):  # 1〜K
                bit = 1 << (next_place - 1)
                if mask & bit:
                    continue  # 既に訪問済み
                
                new_mask = mask | bit
                new_dist = dp[mask][cur] + dist[cur][next_place]
                if new_dist < dp[new_mask][next_place]:
                    dp[new_mask][next_place] = new_dist
    
    # 全ての荷物置き場を訪問した後、スタート地点に戻る
    ans = INF
    for last in range(1, num_places):
        if dp[full_mask][last] < INF:
            ans = min(ans, dp[full_mask][last] + dist[last][0])
    
    print(ans)

if __name__ == "__main__":
    main()

This editorial was generated by claude4.5opus.

投稿日時:
最終更新: