码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - "Sam and sub"

时间:2015-07-15 14:45:05      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:

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;
}

HackerRank - "Sam and sub"

标签:

原文地址:http://www.cnblogs.com/tonix/p/4648045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!