a123困難方向擴充狀態・非負權 Dijkstra

TOI 2026/06 潛力組:駕駛汽車

將格子與進入方向合併,正確計算轉彎增加的損傷。

前往題目練習 →回報教學錯誤令 V=MN,狀態 4V、邊數≤16V;時間 O(V log V)、空間 O(V),M、N≤500。Python 使用緊密陣列保存距離。

解題思路

同一格若由不同方向抵達,下一步是否轉彎可能不同,因此不能只為一格保存一個距離。令 dist[格子][方向] 為以該方向駛入的最小損傷。從 (u,d) 往方向 e 走到 v,增加格值 grid[v],另加上 d≠e 的 1。禁止格不能建立轉移。

所有邊權介於 0~10,可使用 Dijkstra。把起點四個方向都設為 0,等同允許自由選擇第一次方向,不收首次轉彎費;之後每條轉移都按真實方向計費。擴充圖中的每條路徑對應實際駕駛路線,反之亦然,因此首次取出的任一終點方向就是最小總損傷。

Step-by-step animation

公開範例:沿左邊及下邊避開數值 2

回報動畫錯誤
步驟 1 / 3

第一次往下

(0,0)→(1,0),格值 0,首次選方向免費。

(0,0)
(1,0),向下
累積損傷
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int m, n;
    cin >> m >> n;
    int cells = m * n;
    vector<int> g(cells);
    for (int &x : g)
        cin >> x;
    const int INF = 1000000000;
    vector<int> dist(4 * cells, INF);
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    for (int d = 0; d < 4; ++d) {
        dist[d] = 0;
        pq.push({0, d});
    }
    int dr[] = {-1, 1, 0, 0}, dc[] = {0, 0, -1, 1};
    while (!pq.empty()) {
        auto [cost, state] = pq.top();
        pq.pop();
        if (cost != dist[state])
            continue;
        int u = state / 4, d = state % 4;
        if (u == cells - 1) {
            cout << cost << '\n';
            return 0;
        }
        for (int e = 0; e < 4; ++e) {
            int r = u / n + dr[e], c = u % n + dc[e];
            if (r < 0 || r >= m || c < 0 || c >= n)
                continue;
            int v = r * n + c;
            if (g[v] < 0)
                continue;
            int next = 4 * v + e, candidate = cost + g[v] + (d != e);
            if (candidate < dist[next]) {
                dist[next] = candidate;
                pq.push({candidate, next});
            }
        }
    }
    cout << -1 << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多