1140 - How Many Zeroes?
Time Limit: 2 second(s) | Memory Limit: 32 MB |
Jimmy writes down the decimal representations of all naturalnumbers between and including m and n, (m ≤ n). How many zeroeswill 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 andn, (m ≤ n).
Output
For each case, print the case number and the number of zeroeswritten 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[cur][s]表示到当前为止,前面有s个零的有多少答案
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<vector>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=40;
int dig[maxn];
LL N,M;
LL dp[maxn][maxn];
int getsum(int pos)
{
int sum=0;
while(pos>=0)
{
sum=sum*10+dig[pos];
pos--;
}
return sum;
}
LL dfs(int cur,int s,int e,int z)
{
if(cur<0)return z?1:s;
if(!e&&!z&&dp[cur][s]!=-1)return dp[cur][s];
int end=e?dig[cur]:9;
LL ans=0;
for(int i=0;i<=end;i++)
{
if(z&&!i)ans+=dfs(cur-1,0,e&&(i==end),1);
else if(i==0)
{
ans+=dfs(cur-1,s+1,e&&i==end,0);
}
else
ans+=dfs(cur-1,s,e&&i==end,0);
}
if(!e&&!z)dp[cur][s]=ans;
return ans;
}
LL solve(LL n)
{
if(n<0)return 0;
else if(n==0)return 1;
int len=0;
memset(dp,-1,sizeof(dp));
while(n)
{
dig[len++]=n%10;
n/=10;
}
return dfs(len-1,0,1,1);
}
int main()
{
int T,cas=1;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&M,&N);
printf("Case %d: %lld\n",cas++,solve(N)-solve(M-1));
}
return 0;
}