TZOJ 2478 How many 0's?(数位DP)

描述

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 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 mnegative and this line should not be processed.

输出

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.

样例输入

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

样例输出

1
22
92
987654304
3825876150

题意

扫描二维码关注公众号,回复: 7311366 查看本文章

求[l,r]之间0的个数。

题解

数位DP。

[l,r]转化后变成[0,r]-[0,l-1]。

由于从0开始不好处理,可以变成从1开始,然后特判一下0。

考虑每一位数的贡献,比如1234,固定第3位为0的贡献:

1.0为头,00,01,02,03,04,前导0不考虑(除0外的数要考虑这个情况)。

2.0为尾,贡献就是12*10^1=120,意思就是0前面共有1-12(12个数),0后面有0-9(10个数)。

代码中注释的是求0-9的个数。

代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 ll a[10],b[10],l,r;
 5 void dp(ll t,ll *c,ll d)
 6 {
 7     ll n=t/10,m=t%10,temp=n;
 8     //for(int i=1;i<=m;i++)c[i]+=d;
 9     //for(int i=0;i<=9;i++)c[i]+=d*n;
10     c[0]+=d*n;
11     while(temp)
12     {
13         c[temp%10]+=(m+1)*d;
14         temp/=10;
15     }
16     if(n)dp(n-1,c,d*10);
17 }
18  
19 int main()
20 {
21     while(scanf("%lld%lld",&l,&r)!=EOF)
22     {
23         if(l==-1&&r==-1)break;
24         memset(a,0,sizeof(a));
25         memset(b,0,sizeof(b));
26         dp(l-1,a,1);
27         dp(r,b,1);
28         if(l==0)b[0]++;
29         printf("%lld\n",b[0]-a[0]);
30     }
31     return 0;
32 }

猜你喜欢

转载自www.cnblogs.com/taozi1115402474/p/11544148.html