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 |
SPECIAL THANKS: JANE ALAM JAN (DESCRIPTION, SOLUTION, DATASET)
思路:设dp[pos][ cnt ]为当前考虑pos位,之前的数中已经有cnt个0的(不会全是前导零)时候,(pos+1)个数位与之前数位组成的含有0的个数,详见代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int MAXN=15;
ll n,m;
int bit[MAXN];
ll dp[MAXN][MAXN];
ll dfs(int pos,int cnt,int pre,int flag)
{
if(pos == -1) return cnt;
if(flag && pre && dp[pos][cnt]!=-1) return dp[pos][cnt];
ll ans=0;
int x=flag ? 9: bit[pos];
for(int i=0;i<=x;i++){
ans+=dfs(pos-1,cnt+(pre && i==0 ),pre || i,flag || i<x );
}
if(flag && pre) dp[pos][cnt]=ans; //pre必须不为0
return ans;
}
ll solve(ll x)
{
int len=0;
if(!x)
bit[len++]=0;
while(x){
bit[len++]=x%10;
x/=10;
}
return dfs(len-1,0,0,0);
}
int main()
{
//freopen("text.txt","r",stdin);
int T,kase=0;
scanf("%d",&T);
while(T--)
{
memset(dp,-1,sizeof(dp));
kase++;
printf("Case %d: ",kase);
scanf("%lld%lld",&n,&m);
ll ans1,ans2;
ans1= n==0 ? -1 : solve(n-1);
ans2=solve(m);
printf("%lld\n",ans2-ans1);
}
return 0;
}