How Many Zeroes? (数位dp)

Jimmy writes down the decimal representations of all natural numbers between and including m and n, (m ≤ n). How many zeroes will he write down?

Input

Input starts with an integer T (≤ 11000), denoting the number of test cases.

Each case contains two unsigned 32-bit integers m and n, (m ≤ n).

Output

For each case, print the case number and the number of zeroes written down by Jimmy.

Sample Input

5

10 11

100 200

0 500

1234567890 2345678901

0 4294967295

Sample Output

Case 1: 1

Case 2: 22

Case 3: 92

Case 4: 987654304

Case 5: 3825876150


题目大概:

求n到m之间,所有数字含有的0的数量。

思路:

数位dp。

可以从最高位开始一位一位的枚举。

比如一个数是20456.

那么刚开始是第一位是0,这个数不是最高位,后面的数没有限制,所以后面的数有10*剩下的位数种可能。

第一位剩下的都没有0了。

然后当第一位2,第二位,0,这个0是这位的最大数,而且有限制,所以后面的数只能有456+1种可能。

一般就这两种枚举0的可能了。判断条件就是后面的数是否有限制。

具体的就是代码了。


代码:


#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef long long ll;
ll a[20],b[20];
ll dp[20][2][2];

ll sove(int pos,int qian,int lead,int limit)
{
    if(pos==-1)return !qian;
    if(!limit&&dp[pos][lead][limit]!=-1)return dp[pos][lead][limit];
    ll ans=0;
    int end=limit?a[pos]:9;
    for(int i=0;i<=end;i++)
    {
        if(!lead&&i==0)
        {
            if(limit&&i==a[pos])
            {   int t=0;
                for(int j=pos;j>=0;j--)
                {
                    t=t*10+a[j];
                }

                t++;

                ans+=t+sove(pos-1,1,lead&&i==0,1);
            }
            else
            {
                ans+=b[pos]+sove(pos-1,1,lead&&i==0,0);
            }

        }
        else ans+=sove(pos-1,qian||i!=0,lead&&i==0,limit&&(i==a[pos]));

    }
    if(!limit)dp[pos][lead][limit]=ans;
    return ans;
}

ll go(ll x)
{
    int pos=0;
    while(x)
    {
        a[pos++]=x%10;
        x/=10;
    }
    return sove(pos-1,0,1,1);
}
int main()
{
    int t;
    ll n,m;
    b[0]=1;
    for(int i=1;i<=20;i++)
    {
        b[i]=b[i-1]*10;
    }
    scanf("%lld",&t);
    for(int i=1;i<=t;i++)
    {   memset(dp,-1,sizeof(dp));
        scanf("%lld%lld",&n,&m);
        printf("Case %d: %lld\n",i,go(m)-go(n-1));
    }
    return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值