How Many Zeroes? LightOJ - 1140

本文介绍了一种使用数位动态规划(数位DP)解决特定类型数学问题的方法,特别是如何计算给定范围内数字中0的出现次数。通过具体实例展示了数位DP的基本思想和实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值