自学内容网 自学内容网

动态规划——数位统计dp

acwing338.计数问题

#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;
}


原文地址:https://blog.csdn.net/2301_76553467/article/details/138003077

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!