HDU - 4722(初学数位dp)

If we sum up every digit of a number and the result can be exactly divided by 10, we say this number is a good number. 
You are required to count the number of good numbers in the range from A to B, inclusive.

Input

The first line has a number T (T <= 10000) , indicating the number of test cases. 
Each test case comes with a single line with two numbers A and B (0 <= A <= B <= 10 18).

Output

For test case X, output "Case #X: " first, then output the number of good numbers in a single line.

Sample Input

2
1 10
1 20

Sample Output

Case #1: 0
Case #2: 1

题意

这题用找规律的方法也可以做,就是每十个数会出现一个好数。但可以借此题学下数位dp,感觉有点意思,解释放代码里;

#include <iostream>
#include <string.h>
#include<stdio.h>
#include<algorithm>
#include<math.h>
using namespace std;
#define ll long long
ll dp[20][10];// dp[x][y] 表示在x位的时候%10==y的数有几个
int wei[20];//记录每一位上的数
ll re(int s,int j,int bl)//s表示这是第几位数,j表示当前%10剩下的数,bl表判断
{
    if(s==-1)return j==0;//因为位数是从0开始的(看下面ra)所以s=-1时代表取完,返回j==0代表这是不是好数
    if(!bl&&dp[s][j]!=-1)return dp[s][j];//如果之前已经判断过这个位数的就直接返回(一个记忆化搜索)
    ll ans=0;
    int en=bl?wei[s]:9;//判断这一位能到几,比如12 当十位取1时 个位就只能取2
    for(int i=0;i<=en;i++)
        ans+=re(s-1,(j+i)%10,bl&&i==en);//递归每一位加起来
    if(!bl)
        dp[s][j]=ans;//记忆
    return ans;
}
ll ra(ll a)
{
    int xb=0;
    while(a!=0)//每一位存起来
    {
        wei[xb++]=a%10;
        a/=10;
    }
    return re(xb-1,0,1);
}
int main()
{
    int t;
    scanf("%d",&t);
    memset(dp,-1,sizeof(dp));//因为规律是固定的 所以在循环外初始化就好
    for(int i=1;i<=t;i++)
    {
        ll a,b;
        scanf("%lld %lld",&a,&b);
        printf("Case #%d: %lld\n",i,ra(b)-ra(a-1));//a要减一因为a也要判断
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值