动态规划——数位统计dp

acwing338.计数问题

cpp 复制代码
#include<iostream>
#include<cmath>

using namespace std;

int a, b;

int count(int n, int x) //统计从1到n中x的个数
{
    int res = 0;
    int l, r;
    int cnt = 0;
    int m = n;
    
    while(m)
    {
        cnt ++ ; //存储数字n的位数
        m /= 10;
    }
    
    for(int i = 1; i <= cnt; i ++ )
    {
        //以abcdefg为例来看,现在是计算第四位上x的次数,那么现在i=4

        //先计算最高三位为000~abc-1的情况
        r = pow(10, i - 1); //d右边可取到000~999共power10(i-1)个数
        l = n / (r * 10); //d左边可取到000~abc-1共abc种情况,if(x==0)则为001~abc-1共abc-1种
        //abc=n/power10(i)=n/(r*10);

        
        if(x) res += l * r;
        else res += (l - 1) * r;
        
        int d = (n / r) % 10; // n/r=abcd;abcd%10=d;
        //再计算高三位等于abc的情况(只需考虑d>=x,因为d<x就不符合条件)
        if(d == x) res += n % r + 1; //前四位abcd均相同,后三位可取0~efg共efg+1种,efg+1=n%power(i-1)+1=n%r+1;
        else if(d > x) res += r; //此时后三位可取000~999共power10(i-1)种
    }
    return res;
}

int main()
{
    while(cin >> a >> b, a || b)
    {
        if(a > b) swap(a, b);
        
        for(int i = 0; i < 10; i ++ )
            cout << count(b, i) - count(a - 1, i) << " ";
        
        cout << endl;    
    }
    return 0;
}
相关推荐
郑州光合科技余经理29 分钟前
代驾系统架构拆解:订单链路、权限组织与私有化源码交付
开发语言·后端·算法·架构·系统架构·uni-app·php
To_OC3 小时前
LC 35 搜索插入位置:二分查找谁都会,边界条件谁写谁懵
javascript·算法·leetcode
码哥DFS3 小时前
二叉树的直径
开发语言·javascript·算法
营养充电站6 小时前
KMP全栈开发:从Android到AI Agent的技术演进与实践
人工智能·算法·docker·jupyter
技术小黑7 小时前
RNN算法实战系列05 | 天气预测
人工智能·rnn·算法
Ivanqhz9 小时前
php8 use-def链
算法·php
evans在进步10 小时前
LeetCode 189 轮转数组:三次反转原地解决,图解 Java 实现
java·算法·leetcode
歌_顿10 小时前
Drawing_To_Model
算法
龍德明宇10 小时前
AI不会疼-龍德明宇
人工智能·算法·大语言模型llm·负主体性·ai存在论