POJ3286:How many 0's?(数位DP)

时间:2022-12-16 11:38:11

Description

A Benedict monk No.16 writes down the decimal representations of all natural numbers between and including m and n, mn. How many 0's will he write down?

Input

Input consists of a sequence of lines. Each line contains two unsigned 32-bit integers m and n, mn. The last line of input has the value of m negative and this line should not be processed.

Output

For each line of input print one line of output with one integer number giving the number of 0's written down by the monk.

Sample Input

10 11
100 200
0 500
1234567890 2345678901
0 4294967295
-1 -1

Sample Output

1
22
92
987654304
3825876150
 
这道题与POJ2282是一样的,只是这里只计算0的个数而已,只需要将输出改变一下即可
 
 
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
__int64 dp[10][10];

__int64 pow(__int64 a,__int64 b)
{
    __int64 ret=1;
    for(__int64 i=1; i<=b; i++)
        ret*=a;
    return ret;
}

__int64 solve(__int64 n,__int64 pos)
{
    __int64 s[15],len = 0,i,tem;
    while(n)
    {
        s[++len] = n%10;
        n/=10;
    }
    s[0] = 0;
    __int64 ans = 0,cnt = 0;
    for(i = len; i>=1; i--)
    {
        if(pos == 0 && i == len)
        {
            ans+=dp[i-1][pos]*(s[i]-1);
            tem = pow(10,i-1)-1;
            ans+=solve(tem,0);
        }
        else
            ans+=dp[i-1][pos]*s[i];
        ans+=cnt*pow(10,i-1)*s[i];
        if(pos)
        {
            if(s[i]>pos)
                ans+=pow(10,i-1);
            if(s[i]==pos)
                cnt++;
        }
        else if(i!=len)
        {
            if(s[i]>pos)
                ans+=pow(10,i-1);
            if(s[i]==pos)
                cnt++;

        }
    }
    return ans+cnt;
}

int main()
{
    memset(dp,0,sizeof(dp));
    for(__int64 i=1; i<=9; i++)
    {
        for(__int64 j=0; j<=9; j++)
            dp[i][j]=dp[i-1][j]*10+pow(10,i-1);
    }
    __int64 a,b;
    while(scanf("%I64d %I64d",&a,&b),a+b>=0)
    {
        __int64 flag=0;
        if(!a)
            flag = 1;
        if(a>b) swap(a,b);
        printf("%I64d\n",solve(b,0)-solve(a-1,0)+flag);
    }
    return 0;
}