a586中等以適當質因數為邊的BFS

CPE:Number Transformation (UVa 11730)

在只會遞增的整數狀態圖上找最少步數。

前往題目練習 →回報教學錯誤預算 O(U log log U),每筆時間 O(T log T)的寬鬆上界、空間 O(T+U log log U),U=1000。

解題思路

對每個整數v預先建立可用質因數清單。可用的是質數p且p整除v,同時p<v,不能使用1或v本身;因此質數狀態沒有任何下一步。用質數篩枚舉p,再把p放到2p、3p等倍數的清單中就恰好排除了它自己。

每條轉換v→v+p成本都是一步,所以從S做BFS即可。轉換嚴格增加,超過T的狀態不可能再回來,可以直接捨棄。S=T立即是0;S>T一定無法達成。每筆新建距離,找到T輸出距離,否則−1;0 0結束,案例格式Case X: Y。

Step-by-step animation

示意:S=6、T=12

回報動畫錯誤
步驟 1 / 3

展開6

質因數2、3,下一步是8與9。

6→8
6→9
距離6
0
距離8、9
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    const int U = 1000;
    vector<vector<int>> factor(U + 1);
    vector<bool> prime(U + 1, true);
    for (int p = 2; p <= U; ++p)
        if (prime[p])
            for (int v = 2 * p; v <= U; v += p) {
                prime[v] = false;
                factor[v].push_back(p);
            }
    int s, t, tc = 0;
    while (cin >> s >> t && (s || t)) {
        int ans = -1;
        if (s <= t) {
            vector<int> d(t + 1, -1);
            queue<int> q;
            d[s] = 0;
            q.push(s);
            while (!q.empty()) {
                int v = q.front();
                q.pop();
                if (v == t) {
                    ans = d[v];
                    break;
                }
                for (int p : factor[v])
                    if (v + p <= t && d[v + p] == -1) {
                        d[v + p] = d[v] + 1;
                        q.push(v + p);
                    }
            }
        }
        cout << "Case " << ++tc << ": " << ans << '\n';
    }
}

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

更多