How many 0's?
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 2844 | Accepted: 1506 |
Description
A Benedict monk No.16 writes down the decimal representations of all natural numbers between and including m and n, m ≤ 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 n, m ≤ 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
Source
Waterloo Local Contest, 2006.5.27
dp的思路很容易看出来,关键是处理好细节,调试了很长时间的代码。
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <cstdio>
#define N 30
using namespace std;
__int64 dp1[N],dp2[N];
int dig[N];
int Top;
__int64 ba[N];
int main()
{
//freopen("data.txt","r",stdin);
__int64 f();
memset(dp1,0,sizeof(dp1));
memset(dp2,0,sizeof(dp2));
dp1[1] = dp2[1] = 1;
ba[0] = 1;
ba[1] = 10;
for(int i=2;i<=11;i++)
{
dp1[i] = dp2[i-1]*9;
dp2[i] = 10*dp2[i-1]+ba[i-1];
ba[i] = ba[i-1] * 10;
}
__int64 n,m;
while(scanf("%I64d %I64d",&n,&m)!=EOF)
{
if(n<0)
{
break;
}
Top = 0;
n-=1;
__int64 res1,res2;
if(n==-1)
{
res1 = 0;
}else
{
if(n==0)
{
dig[Top++] = 0;
}
while(n!=0)
{
dig[Top++] = n%10;
n = n/10;
}
res1=f();
}
Top = 0;
if(m==0)
{
dig[Top++] = 0;
}
while(m!=0)
{
dig[Top++] = m%10;
m = m/10;
}
res2 = f();
printf("%I64d\n",res2-res1);
}
return 0;
}
__int64 f()
{
__int64 res = 0;
for(int i=1;i<=Top-1;i++)
{
res+=dp1[i];
}
//cout<<res<<endl;
int t;
for(int i=Top-1;i>=0;i--)
{
if(i==Top-1&&Top>1)
{
t = 1;
}else
{
t = 0;
}
for(int j=t;j<=dig[i]-1;j++)
{
res+=dp2[i];
if(j==0)
{
res+=ba[i];
}
}
}
for(int i=Top-1;i>=0;i--)
{
if(dig[i]==0)
{
__int64 sum = 0;
for(int j=i-1;j>=0;j--)
{
sum = sum*10+dig[j];
}
sum+=1;
res+=sum;
}
}
return res;
}