51Nod 1042 数字0-9的数量(前导0的数位dp)

题目链接:https://vjudge.net/contest/374535#problem/F
给出一段区间a-b,统计这个区间内0-9出现的次数。
比如 10-19,1出现11次(10,11,12,13,14,15,16,17,18,19,其中11包括2个1),其余数字各出现1次。

Input
两个数a,b(1 <= a <= b <= 10^18)

Output
输出共10行,分别是0-9出现的次数

Sample Input

10 19

Sample Output

1
11
1
1
1
1
1
1
1
1

完整代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long LL;
int a[30];
LL dp[30][30][30];
LL dfs(int pos,int sta,int lead,int limt,int number)///位数 状态  前导0 最高位限制 目标为number
{
    if(pos==-1)
        return sta;///所有位已经搜索完,返回找到的number的数量
    if(!lead&&!limt&&dp[pos][number][sta]!=-1)
        return dp[pos][number][sta];
    int up=limt?a[pos]:9;
    LL res=0;
    for(int i=0; i<=up; i++)
    {
        if(lead&&i==0)///前导0标记存在,并且当前位也为0,当前位也当做前导0
            res+=dfs(pos-1,sta,lead,limt&&i==up,number);
        else
            res+=dfs(pos-1,sta+(i==number),lead&&i==0,limt&i==up,number);///i==number的值为0或1
    }
    if(!limt&&!lead)
        dp[pos][number][sta]=res;
    return res;
}
LL solve(LL x,int number)
{
    int tot=0;
    while(x)
    {
        a[tot++]=x%10;
        x/=10;
    }
    return dfs(tot-1,0,1,1,number);
}
int main()
{
    LL m,n;
    scanf("%lld%lld",&m,&n);
    memset(dp,-1,sizeof(dp));
    for(int i=0; i<=9; i++)///统计区间[m,n]每一个i的数量
        printf("%lld\n",solve(n,i)-solve(m-1,i));
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zaiyang遇见

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值