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

本文介绍了一种使用数位动态规划的方法来解决一个特定的问题:在1到n的范围内有多少个幸运数。幸运数被定义为该数等于其各位数字之和的倍数。通过数位动态规划对不同数位和的情况进行讨论,最终得出了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

 

描述

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

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

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

输入

第一行一个正整数 n

1 ≤ n ≤ 1012

输出

输出有几个幸运数

 

 

POINT:

 dp[14][120][120][120];//pos sum remain 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[14];

LL dp[14][120][120][120];//pos sum rem mod

LL dfs(LL pos,LL sum,LL m,bool limit,LL mod)
{
    if(!pos) return (!sum)&&(!m);
    if(!limit&&dp[pos][sum][m][mod]!=-1) return dp[pos][sum][m][mod];
    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][mod]=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++){
        ans+=dfs(cnt,i,0,1,i);
    }
    return ans;
}
int main()
{
    int T;
    scanf("%d",&T);
    int cas=0;
    memset(dp,-1,sizeof dp);
    while(T--){
        LL n;
        scanf("%lld",&n);
        printf("Case %d: %lld\n",++cas,solve(n));
    }
    return 0;
}

 

 

 

 

 

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

 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值