BZOJ1833 [ZJOI2010]count 数字计数

来源:互联网 发布:围棋软件知乎 编辑:程序博客网 时间:2024/04/30 00:50

Description

  • 给定两个正整数ab,求在[a,b]中的所有整数中,每个数码(digit)各出现了多少次。

Input

  • 输入文件中仅包含一行两个整数a,b,含义如上所述。

Output

  • 输出文件中包含一行10个整数,分别表示09[a,b]中出现了多少次。

Sample Input

  • 1 99

Sample Output

  • 9 20 20 20 20 20 20 20 20 20

HINT

  • 30%的数据中:ab106
  • 100%的数据中:ab1012

Source

  • Day1

Problem Address

  • BZOJ1833 洛谷2602

Solution 数位DP(注释在代码中给出)

Code

#include <iostream>#include <cstdio>#include <cstring>using namespace std;const int Maxn = 0x3f3f3f3f;const int N = 15;typedef long long ll;ll f[N], tn[N], num[N], sta[N], stb[N], a, b;inline ll get(){    char ch; bool f = false; ll res = 0;    while (((ch = getchar()) < '0' || ch > '9') && ch != '-');    if (ch == '-') f = true;     else res = ch - '0';    while ((ch = getchar()) >='0' && ch <= '9')        res = (res << 3) + (res << 1) + ch - '0';    return f? ~res + 1 : res;}inline void put(ll x){    if (x < 0)      x = ~x + 1, putchar('-');    if (x > 9) put(x / 10);    putchar(x % 10 + 48);}inline void Find(ll x, ll *st){    if (x == 0) return;    ll res = x; int m = 0;    while (x) num[++m] = x % 10, x /= 10;    //拆出每一位,记为num[i]     for (int i = 1; i < m; ++i)    //对于1~m-1位数,我们不用考虑数的上限(<=x), 所以可以先处理     {        st[0] += (f[i - 1] << 3) + f[i - 1];        //真正求解的时候不含前导0(第i位不存在0),         //所以对于前i-1位存在的每一个数字(0~9),第i位只有9种可能。         //同时对于0,前i-1位的每一种排列方案也要排除。         for (int j = 1; j < 10; ++j)          st[j] += (f[i - 1] << 3) + f[i - 1] + tn[i - 1];    }    res -= num[m] * tn[m - 1]; //接下来我们考虑m位数     for (int i = 1; i < num[m]; ++i) st[i] += tn[m - 1];    //对于第m位的1~num[m]-1(不含前导0),     //前m-1位的每一种排列仍可直接算作一种方案。     for (int i = 0; i < 10; ++i)      st[i] += f[m - 1] * (num[m] - 1);    //对于第1~m-1位出现的每一个数字,     //数字1~num[m]-1仍可直接算作一种方案。     st[num[m]] += res + 1;    //保持最高位的上限数字不动,     //方案数即为扣除最高位的总方案数(0~res)。     for (int i = m - 1; i; --i)    {        res -= num[i] * tn[i - 1];        //从高位删到低位,         //每一位都要像我们刚才的第m位处理,但不用考虑前导0。         for (int j = 0; j < num[i]; ++j) st[j] += tn[i - 1];        for (int j = 0; j < 10; ++j) st[j] += f[i - 1] * num[i];        st[num[i]] += res + 1;    } }int main(){    a = get(); b = get(); tn[0] = 1;    //先计算出[1,a-1],[1,b]中每个数字出现的个数,然后相减即可。     //问题变为:给一个数n,求1,2,…,n中每个数字出现的次数。      for (int i = 1; i < 15; ++i)    {        f[i] = (f[i - 1] << 3) + (f[i - 1] << 1) + tn[i - 1];        //首先,允许前导0,也不考虑数大小的上限,设位数为 i。         //前i位每种数字出现的次数是相同的,记为 f[i]。         //不难得出递推式 f[i]=10*f[i-1]+10^(i-1)。         //10*f[i-1]表示对于前i-1位出现的每一个数字,         //第i位都存在10种方案(0~9);        //10^(i-1)表示对于第i位出现的唯一一个数字,         //前i-1位的每一种排列都算作一种方案。         tn[i] = (tn[i - 1] << 3) + (tn[i - 1] << 1);    }      Find(a - 1, sta); Find(b, stb);    for (int i = 0; i < 9; ++i) put(stb[i] - sta[i]), putchar(' ');     return put(stb[9] - sta[9]), 0; }
原创粉丝点击