How Many Zeroes? LightOJ - 1140

題目:

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
5
10 11
100 200
0 500
1234567890 2345678901
0 4294967295

Sample Output
Case 1: 1
Case 2: 22
Case 3: 92
Case 4: 987654304
Case 5: 3825876150

大意:

給你一個範圍,求這個範圍內的數字中出現0的次數

思路:

數位dp,注意按位dp時出現前導0

代碼:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 1000000000;
const int maxn = 123456;
int T;
ll l,r,ans;
ll a[25];
ll dp[25][25];//dp[i][j]處理到第i位時前面出現了j個0

ll dfs(int pos,bool limt,int cnt,bool is0)//is0表示前面是否一直爲0
{
    if(!pos)//計算到最後一位
        return is0?1:cnt;//前導0之類的算一個0
    ll sum=0;
    if(!limt&&dp[pos][cnt]!=-1&&!is0)
        return dp[pos][cnt];
    int k=(limt?a[pos]:9);
    for(int i=0;i<=k;i++)
    {
        if(is0)
            sum+=dfs(pos-1,limt&&(i==k),0,i==0);
        else
            sum+=dfs(pos-1,limt&&(i==k),cnt+(i==0),0);
    }
    if(!limt&&!is0)
        dp[pos][cnt]=sum;
    return sum;
}

ll solve(ll k)
{
    int p=0;
    while(k)
    {
        a[++p]=k%10;
        k/=10;
    }
    return dfs(p,1,0,1);
}

int main()
{
    int no=0;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%lld%lld",&l,&r);
        memset(dp,-1,sizeof(dp));
        printf("Case %d: ",++no);
        printf("%lld\n",solve(r)-solve(l-1));
    }
    return 0;
}
發佈了90 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章