CF1932E 题解

· · 题解

思路

首先就拿样例二 12345 来看吧。万位没啥好说,肯定只要转 1 次。千位,从 12345\to02345 需要转 1\times10=10 次,再加上 02345\to00345 的 2 次,共 12 次。剩下的百位、十位、个位则分别是 123,1234,12345 次。所以答案就是把这个数的每个前缀都加起来。然后暴力加前缀是不可取的,我们列个数据会发现,这个数也可以通过 11111+2222+333+44+5 来计算。然后我们差分一下,然后高精度进位就好。

代码

# include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
int t, n, ans[400005], x;
string a;
int main () {
    ios::sync_with_stdio (0);
    cin.tie (0);
    cout.tie (0);
    cin >> t;
    while (t --) {
        cin >> n >> a;
        for (int i = 0; i <= n; ++ i)
            ans[i] = 0;
        for (int i = 0; i < n; ++ i) {
            x = a[n - i - 1] - '0';
            ans[0] += x, ans[i + 1] -= x;
        }
        for (int i = 0; i < n; ++ i)
            ans[i + 1] += ans[i];
        for (int i = 0; i < n; ++ i)
            ans[i + 1] += ans[i] / 10, ans[i] %= 10;
        while (! ans[n])
            -- n;
        while (~n)
            cout << ans[n], -- n;
        cout << '\n';
    }
    return 0;
}