现在的位置: 首页 > 综合 > 正文

HDU 4507 吉哥系列故事——恨7不成妻(数位DP)

2018年04月04日 ⁄ 综合 ⁄ 共 1507字 ⁄ 字号 评论关闭

题目链接:Click here~~

题意:

中文题不解释。

解题思路:

之前做的都是统计满足那些性质的数的 count,这次直接蹦到统计 square sum 了。。。

先考虑如何统计 sum。

统计 sum 维护两个值 count 和 sum 就可以了。

想象状态转移时,相当于在一个具有同样性质的后缀的数的集合前面,加某个数字。

那么,sum[new_state] = Σ{ sum[old_state] + (number to add at the postion) * (its base) * count[old_state] }。(语言不好描述,看式子吧。。。)

类似的,维护三个值 count & sum & square sum 可以解决这个问题了。自己想一下吧。O(∩_∩)O。

启发:原式是 a[1]^2 + a[2]^2 + … + a[n]^2,新式是 (a[1]+b)^2 + (a[2]+b)^2 + … + (a[n]+b)^2。

#include <math.h>
#include <string>
#include <stdio.h>
#include <string.h>

using namespace std;

typedef long long LL;
typedef pair< int,pair<LL,LL> > PILL;

#define F first
#define S second
#define MP make_pair

const int mod = 1e9 + 7;

int digit[20];

LL pow10[20];

PILL dp[20][7][7][2];

bool vis[20][7][7][2];

PILL dfs(int len,int sum,int remain,bool contain,bool fp)
{
    if(!len)
        if(!contain && sum && remain)
            return MP(1,MP(0LL,0LL));
        else
            return MP(0,MP(0LL,0LL));
    if(!fp && vis[len][sum][remain][contain])
        return dp[len][sum][remain][contain];
    PILL ret = MP(0,MP(0,0));
    int fpmax = fp ? digit[len] : 9;
    for(int i=0;i<=fpmax;i++)
    {
        PILL nxt = dfs(len-1,(sum + i) % 7,(remain * 10 + i) % 7,contain | (i == 7),fp && i == fpmax);
        LL pref = i * pow10[len-1] % mod;
        (ret.F += nxt.F) %= mod;
        (ret.S.F += nxt.S.F + pref * nxt.F) %= mod;
        (ret.S.S += nxt.S.S + pref * pref % mod * nxt.F + 2 * pref * nxt.S.F) %= mod;
    }
    if(!fp)
    {
        vis[len][sum][remain][contain] = true;
        dp[len][sum][remain][contain] = ret;
    }
    return ret;
}

long long f(long long n)
{
    int len = 0;
    while(n)
    {
        digit[++len] = n % 10;
        n /= 10;
    }
    return dfs(len,0,0,0,true).S.S;
}

int main()
{
    pow10[0] = 1;
    for(int i=1;i<20;i++)
        pow10[i] = pow10[i-1] * 10 % mod;
    int T;
    scanf("%d",&T);
    while(T--)
    {
        long long a,b;
        scanf("%I64d%I64d",&a,&b);
        printf("%I64d\n",(f(b) - f(a-1) + mod) % mod);
    }
    return 0;
}

抱歉!评论已关闭.