hihoCoder 编程练习赛69 - D 幸运数字(数位DP)

题目

描述

定义一个数字 x 是幸运的,当且仅当 x 是 x 十进制下所有数位的和的倍数

例如 1..9 所有数都是幸运数,120 也是幸运数

现在给定 n ,求 [1, n] 中有几个幸运数

输入

第一行一个正整数 n

1 ≤ n ≤ 1012

输出

输出有几个幸运数

POINT:

分所有数位的和的不同情况讨论进行多次数位DP。

所以总共需要1到n长度×9次数位DP。

每次确定了他们的所有数位的和。

dfs(LL pos,LL sum,LL m,bool limit,LL mod)

sum表示要达到所有数位的和还剩余多少。

m就是当前对mod取模式多少。

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <map>
using namespace std;
#define LL long long
const LL maxn = 1e6+33;

LL num[13];

LL dp[13][200][200];

LL dfs(LL pos,LL sum,LL m,bool limit,LL mod)
{
    if(!pos) return (!sum)&&(!m);
    if(!limit&&dp[pos][sum][m]!=-1) return dp[pos][sum][m];
    LL up=limit?num[pos]:9;
    LL temp=0;
    for(int i=0;i<=up&&i<=sum;i++){
        temp+=dfs(pos-1,sum-i,(m*10+i)%mod,limit&&i==num[pos],mod);
    }
    if(!limit) dp[pos][sum][m]=temp;
    return temp;

}


LL solve(LL x)
{
    LL cnt=0;
    while(x){
        num[++cnt]=x%10;
        x=x/10;
    }
    LL ans=0;
    for(LL i=1;i<=cnt*9;i++){
        memset(dp,-1,sizeof dp);
        ans+=dfs(cnt,i,0,1,i);
    }
    return ans;
}
int main()
{

    LL n;
    scanf("%lld",&n);
    printf("%lld\n",solve(n));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/mr_treeeee/article/details/81157312