首页 > 其他 > 详细

POJ - 3286 - How many 0's? 【数位DP】

时间:2016-04-24 23:04:24      阅读:258      评论:0      收藏:0      [点我收藏+]

How many 0‘s?

Time Limit: 1000MS   Memory Limit: 65536KB   64bit IO Format: %I64d & %I64u

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, m+1, ..., n时,总共写下了多少个0

所以,枚举0出现在每一位上时的情况数,将全部情况数汇总求和,即可不多不少地计算总数。

这里要注意,我们写数字时不可能写出一个数字是0开头的(不允许前导0),这一点留心。

#include <cstdio>
#include <iostream>

using namespace std;

typedef long long LL;

int base[11];

void Init()
{
    base[1] = 1;
    for(int i=2; i<=10; i++) {
        base[i] = base[i-1] * 10;
    }
}

LL f(LL x)
{
    if(x == -1)    return 0;
    
    LL ret = 1; // 0的情况,下面没有讨论,在此补上
    LL temp = x;
    for(int i=1; temp/10; i++, temp/=10) { // 因为最高位不用(不允许前导0),所以判断条件写为 temp/10
        int now = temp % 10;
        LL l = x / base[i+1];
        if(now) {
            ret += l * base[i];
        } else {
            LL r = x % base[i];
            ret += (l-1) * base[i] + r + 1LL;
        }
    }
    return ret;
}

int main ()
{
    Init();
    LL m, n;
    while(scanf("%lld%lld", &m, &n) != EOF && m!=-1) {
        printf("%lld\n", f(n) - f(m-1));
    }
    
    return 0;
}

 

POJ - 3286 - How many 0's? 【数位DP】

原文:http://www.cnblogs.com/AcIsFun/p/5428661.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!