HackerRank

Brutal-force solution is not hard to think about. But linear space input usually indicates O(n) DP solution.

State design: dp[i]: total sum until index i; and then you need some number manipulation to figure out the equation.

https://www.hackerrank.com/challenges/sam-and-substrings/editorial

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;

#define MOD 1000000007

size_t calc(string &str)
{
    size_t len = str.length();
    vector<size_t> dp(len + 1);
    dp[0] = str[0] - '0';
    for (int i = 1; i < len; i++)
    {
        size_t curr = (i + 1) * (str[i] - '0') % MOD;
        curr += 10 * dp[i - 1] % MOD;
        dp[i] = curr;
    }
    //    Get sum
    size_t ret = 0;
    for (int i = 0; i < len; i++)
        ret = (ret + dp[i]) % MOD;
    return ret;
}

int main()
{
    string in; cin >> in;
    size_t len = in.length();
    size_t r = calc(in);
    cout << r << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/tonix/p/4648045.html