数位dp poj3286 How many 0's?

来源:互联网 发布:国外期刊 数据库 编辑:程序博客网 时间:2024/05/21 09:29

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 11100 2000 5001234567890 23456789010 4294967295-1 -1

Sample Output

122929876543043825876150

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

题意:就是给一个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 __int64LL 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 11100 2000 5001234567890 23456789010 4294967295-1 -1*/