1140 - How Many Zeroes?
Time Limit: 2 second(s) | Memory Limit: 32 MB |
Jimmy writes down the decimal representations of all natural numbers between and including m and n, (m ≤ n). How many zeroes will he write down?
Input
Input starts with an integer T (≤ 11000), denoting the number of test cases.
Each case contains two unsigned 32-bit integers m and n, (m ≤ n).
Output
For each case, print the case number and the number of zeroes written down by Jimmy.
Sample Input | Output for Sample Input |
5 10 11 100 200 0 500 1234567890 2345678901 0 4294967295 | Case 1: 1 Case 2: 22 Case 3: 92 Case 4: 987654304 Case 5: 3825876150 |
数位DP。
dp[pos][sum][pre]:当位数为pos时,0的个数(不含前缀0)为sum,pre判断是否为前缀0.
#include <iostream>
#include<string.h>
using namespace std;
long long dp[20][20][2];
int dight[20];
long long dfs(int pos,int sum,bool pre,bool flag)
{ int i;
long long ans=0;
if(pos==-1)return (sum+pre);
if(!flag&&dp[pos][sum][pre]!=-1)return dp[pos][sum][pre];
int u=flag?dight[pos]:9;
for(i=0;i<=u;i++)
ans=ans+dfs(pos-1,sum+(!pre&&i==0),pre&&i==0,flag&&i==u);
if(!flag)dp[pos][sum][pre]=ans;
return ans;
}
long long fun(long long n)
{
int len=0;
while(n)
{
dight[len++]=n%10;
n=n/10;
}
dfs(len-1,0,1,1);
}
int main()
{
int t,i;
long long n,m;
cin>>t;
for(i=1;i<=t;i++)
{ memset(dp,-1,sizeof(dp));
cin>>n>>m;
cout<<"Case "<<i<<": ";
cout<<fun(m)-fun(n-1)<<endl;
}
return 0;
}