b406困難

七倍迴文修復

運用鏡像位置配對與模 7 最小費用計數,正確求解本題並處理邊界情況。

解題思路

迴文由每對鏡像位置的一個數字決定,中間單格獨立。

第 i 對選 d 的費用為 |S[i]-d|+|S[n-1-i]-d|,模 7 貢獻是 d×(10^i+10^(n-1-i));中間單格只算一次。

對已處理配對的餘數維護最小費用及達成個數;較小費用取代,相等費用相加。外層首位排除 0,最後取餘數 0。每條選字路徑唯一對應一個結果迴文。

時間 O(n×7×10),空間 O(n),包含輸入字串與冪次表;DP 額外 O(7)。

Step-by-step animation

教學例子:輸入 121,外側兩位必須相同且非零。

回報動畫錯誤
步驟 1 / 3

步驟 1

輸入 121,外側兩位必須相同且非零。

1
2
1
狀態
目標模 7 = 0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    string s;
    cin >> s;
    int n = s.size(), M = 1000000007;
    vector<int> pw(n, 1);
    for (int i = 1; i < n; i++)
        pw[i] = pw[i - 1] * 10 % 7;
    const int INF = 1000000000;
    vector<int> dp(7, INF), cnt(7);
    dp[0] = 0;
    cnt[0] = 1;
    for (int i = 0; i < (n + 1) / 2; i++) {
        int j = n - 1 - i, c = (pw[i] + (i == j ? 0 : pw[j])) % 7;
        vector<int> nd(7, INF), nc(7);
        for (int r = 0; r < 7; r++)
            if (dp[r] != INF)
                for (int d = (i == 0 && n > 1 ? 1 : 0); d <= 9; d++) {
                    int z = (r + c * d) % 7, cost = dp[r] + abs(s[i] - '0' - d) +
                                                    (i == j ? 0 : abs(s[j] - '0' - d));
                    if (cost < nd[z]) {
                        nd[z] = cost;
                        nc[z] = cnt[r];
                    } else if (cost == nd[z])
                        nc[z] = (nc[z] + cnt[r]) % M;
                }
        dp.swap(nd);
        cnt.swap(nc);
    }
    cout << dp[0] << ' ' << cnt[0] << '\n';
}

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

更多