玲珑oj 1067 - Digital Count (数位DP

本文解析了一道名为1067-DigitalCount的问题,该问题要求计算一个给定区间内所有整数中特定数字出现的总次数。通过使用数位DP的方法,文章提供了一个AC代码示例,详细展示了如何手动实现pow函数以避免精度损失,并通过具体的样例输入输出说明了解决方案的有效性。

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

1067 - Digital Count

Description

Given three integers a, b, P, count the total number of digit P appearing in all integers from a to b.

Input

The first line is a single integer T, indicating the number of test cases.

For each test case:

There are only three numbers
a,b,P (0≤a≤b≤231-1, 0

Output

For each test cases:

Print the total appearances of digit P from a to b in a single line.

Sample Input

2
1 10000 1
1 10 1

Sample Output

4001
2

题意

嗯 给一个区间和一个数字 求区间内一共有多少个数字

题解:

数位DP板子题 第一次打玲珑杯遇到的 当时想了各种姿势wa 时隔版半年终于抄板子A了对依水可喜可贺啊2333

AC代码

#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
#define ll long long
const int mod = 1e9+7;
ll dp[100];
ll Pow (ll a, ll b)    //手写 pow函数 防止精度缺失 
{
    ll ans = 1;
    while(b) {
        if(b&1) ans = ans*a;
        b /= 2;
        a = a*a;
    }
return ans;
}
void init()
{
    memset(dp,0,sizeof(dp));
    for(int i = 1;i <= 18; i++) {
        dp[i] = i*Pow(10,i-1);                //计算出现的次数 比如00 到 99 都是20 
    }
} 
ll sum(ll x, ll k)
{
    ll radix = 1, tail = 0, res = 0;
    ll ans = x;
    ll digit = 0, len = 0;
    while(x) {
        len++;
        digit = x%10;
        x /= 10;
        if(digit > k) {
            res += radix + digit*dp[len-1];; 
        }
        else  if(digit == k) {
            res += tail + 1 + digit*dp[len-1];
        }
        else {
            res += digit*dp[len-1];
        }
        tail += digit*radix;
        radix *= 10;
    }
    if(k == 0) {                 // 去除重复的个数  比如 000-999 每次都重复计算了0的个数 需要减掉 
        ll m = 1;
        while(ans) {
            ans /= 10;
            res -= m;
            m *= 10;
        }
    }
return res;
} 


int main()
{
    int T;
    scanf("%d",&T);
    while(T--) {
        ll a, b;
        int x;
        scanf("%lld%lld%d",&a,&b,&x);
        init();
            printf("%lld\n",sum(b,x)-sum(a-1,x));
    }
 return 0;   
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值