解題思路
從 x 可走到 x±1(成本 2)、x±2、2x、floor(x/2)(成本 3)。只加入 0 到 1000000 的合法結果,求 a 到 b 的最短距離。
所有邊權為正且最多 3,可用四個循環桶代替優先佇列。依距離由小到大取出狀態,忽略已過期項目;第一次取出 b 時距離已最短。桶索引對 4 取餘不改變處理順序,因為新距離至多比目前大 3。
令 V=1000001,每點至多 6 邊,時間 O(V),空間 O(V)。 Python read().split() 另需 O(I) 輸入文字與詞元暫存,I 為總輸入大小。
Step-by-step animation
教學示意(以步驟描述中的輸入為準)
步驟 1 / 3
起點
示意由 0 變成 8。
0
- 成本
- 0
#include <bits/stdc++.h>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
const int V = 1000001, INF = 1e9;
vector<int> d(V, INF);
array<deque<int>, 4> q;
d[a] = 0;
q[0].push_back(a);
int pending = 1, t = 0;
while (pending) {
while (q[t % 4].empty())
t++;
int x = q[t % 4].front();
q[t % 4].pop_front();
pending--;
if (d[x] != t)
continue;
if (x == b) {
cout << t << '\n';
break;
}
int y[] = {x - 1, x + 1, x - 2, x + 2, x * 2, x / 2};
for (int k = 0; k < 6; k++)
if (y[k] >= 0 && y[k] < V) {
int nd = t + (k < 2 ? 2 : 3);
if (nd < d[y[k]]) {
d[y[k]] = nd;
q[nd % 4].push_back(y[k]);
pending++;
}
}
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。