数位dp(三)——hdu4507 吉哥系列故事——恨7不成妻

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4507
题目大意
问区间[a,b]不和7有关数字的平方和。
如果一个整数符合下面3个条件之一,那么我们就说这个整数和7有关
1、整数中某一位是7;
2、整数的每一位加起来的和是7的整数倍;
3、这个整数是7的整数倍;
解题思路
挺难的数位dp的题,首先难点在于我们需要dp的不止是数量,还需要dp所有数的和以及平方和。定义结构体node{tot,s1,s2},tot表示数量,s1表示和,s2表示平方和。node dp[pos][sum1][sum2]表示到第pos位,每一位加和%7为sum1,当前数%7为sum2的满足条件的状态。我们设当前状态为ans,子状态为tmp。
首先,tot是和普通的数位dp一样的状态转移。
ans.tot+=tmp.tot

其次,就是和的转移(需要利用和去转移平方和),设高位加数为high=i*10pos-1
ans.s1+=tmp.s1+tmp.tot*high

最后,是平方和的转移
在这里插入图片描述
然后套数位dp模板,注意返回的类型是结构体。
AC代码

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
int a[20];
ll num[20];
//dp[pos][sum1][sum2]表示到第pos位数位之和%7为sum1当前整体%7为sum2满足条件数的状态
struct node
{
    ll tot,s1,s2;
    node()
    {
        tot=-1;
        s1=s2=0;
    }
}dp[20][12][12];
ll x,y;
int cnt,T;
void init(ll n)
{
    cnt=0;
    while(n)
    {
        a[++cnt]=n%10;
        n/=10;
    }
}
node dfs(int pos,int limit,int sum1,int sum2)
{
    if(!pos)
    {
        node t;
        t.s1=t.s2=0;
        if(!sum1||!sum2)
        t.tot=0;
        else
        t.tot=1;
        return t;
    }
    if(!limit&&dp[pos][sum1][sum2].tot!=-1)
    return dp[pos][sum1][sum2];
    int up=limit?a[pos]:9;
    node ans;
    ans.tot=ans.s1=ans.s2=0;
    for(int i=0;i<=up;++i)
    {
        if(i!=7)
        {
            node tmp=dfs(pos-1,limit&&i==up,(sum1+i)%7,(sum2*10+i)%7);
            ll high=i*num[pos-1]%mod;
            ans.tot=(ans.tot+tmp.tot)%mod;
            ans.s1=(ans.s1+(tmp.s1+tmp.tot*high%mod)%mod)%mod;
            ans.s2=(ans.s2+(tmp.s2+2*high%mod*tmp.s1%mod+high*high%mod*tmp.tot%mod)%mod)%mod;
        }
    }
    if(!limit)
    dp[pos][sum1][sum2]=ans;
    return ans;
}
int main()
{
    memset(dp,-1,sizeof(dp));//别忘记初始化
    scanf("%d",&T);
    num[0]=1;
    for(int i=1;i<=18;++i)
    num[i]=num[i-1]*10%mod;
    while(T--)
    {
        scanf("%lld%lld",&x,&y);
        init(x-1);
        node l=dfs(cnt,1,0,0);
        init(y);
        node r=dfs(cnt,1,0,0);
        printf("%lld\n",(r.s2-l.s2+mod)%mod);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44491423/article/details/108158003