b171中等

108 台中區資訊學科能力競賽(2019)|找出最大值

B的數字必須保持原順序,只能在其間或尾端插0。

解題思路

B的數字必須保持原順序,只能在其間或尾端插0。

可將B左側補0到與A同長,枚舉這個固定長度內B各數字的保序位置,其他位置填0。這也涵蓋少插0的情形,因為前導0不改變數值。

對每個得到的B′計算abs(A-B′),逐位取餘數累加,取最大。每個合法插法都有對應位置選擇,重複數值無妨。

時間 O(C(m,n)·m),空間 O(m),m<18。

Step-by-step animation

教學小例:保序插零的完整枚舉

回報動畫錯誤
步驟 1 / 3

A=100、B=1

補滿三位的候選001、010、100

補滿三位的候選001、010、100
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        string a, b;
        cin >> a >> b;
        long long A = stoll(a);
        int m = a.size(), n = b.size(), ans = 0;
        function<void(int, int, long long)> f = [&](int i, int j, long long x) {
            if (i == m) {
                if (j == n) {
                    long long z = llabs(A - x);
                    int s = 0;
                    while (z) {
                        s += z % 10;
                        z /= 10;
                    }
                    ans = max(ans, s);
                }
                return;
            }
            if (m - i > n - j)
                f(i + 1, j, x * 10);
            if (j < n)
                f(i + 1, j + 1, x * 10 + b[j] - '0');
        };
        f(0, 0, 0);
        cout << ans << '\n';
    }
}

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

更多