数位dp poj3286 How many 0's?

Description

A Benedict monk No.16 writes down the decimal representations of all natural numbers between and including m and nm ≤ n. 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 nm ≤ n. 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

很久没写题解了,今天在无聊是写一篇!

题意:就是给一个m和n,求出m到n这个范围内0的个数。

分析:

    这应该是一个数位dp要求0的个数,那么我们把它转化成求[0,x]这个范围的0的个数。这样便于计算。

    现在以21035为例:

   

 首先 0 肯定是一个,sum 赋初值为 1

        个位数是 0

                个位数前面的数不能是 0,能够取的数就是 [1, 2103],个位后面没有了

                那么 sum+=2103*1

        十位数是 0

                十位数前面的数不能是 0,能够取的数就是 [1, 210],由于 0 比 3 小,十位后面可以取 [0, 9]

                那么 sum+=210*10

        百位数是 0

                百位数前面的数不能是 0,能够取的数就是 [1, 21],由于 0 是等于 0 的,这里就要特殊处理下了:

                百位数前面的数如果是在 [1, 20] 中的,百位数后面的数可以取的就是 [0, 99]

                百位数前面的数如果取的是 21,百位数后面的数就只能取 [0, 35]

                那么,sum+=20*100+36

        ......

以此类推就能确定。



#include<iostream>
#include<fstream>
#include<iomanip>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<sstream>
#include<cassert>
using namespace std;
#define LL __int64
LL num[20];
LL n,m;
LL fun(LL x) {
    if(x<0)return 0;
    LL sum=1;
    int i=1;
    while(1) {
        if(num[i]>x) break;
        LL q=x/num[i];
        LL r=x%num[i-1];
        LL n=(x%num[i]-x%num[i-1])/num[i-1];
        if(n==0)
            sum+=(q-1)*num[i-1]+r+1;
        else
            sum+=q*num[i-1];
        i++;
    }
    return sum;
}
int main() {
    num[0]=1;
    for(int i=1; i<20; i++)
        num[i]=num[i-1]*10;
    while(~scanf("%I64d%I64d",&n,&m)) {
        if(n==-1&&m==-1)
            break;
        printf("%I64d\n",fun(m)-fun(n-1));
    }

    return 0;
}

/*

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



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值