Description
- 给定两个正整数
a
和b,求在
[a,b]
中的所有整数中,每个数码
(digit)
各出现了多少次。
- 输入文件中仅包含一行两个整数
a,b
,含义如上所述。
Output
- 输出文件中包含一行
10
个整数,分别表示
0−9
在
[a,b]
中出现了多少次。
Sample Output
- 9 20 20 20 20 20 20 20 20 20
HINT
- 30%的数据中:
a≤b≤106
- 100%的数据中:
a≤b≤1012
Source
Problem Address
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;
for (int i = 1; i < m; ++i)
{
st[0] += (f[i - 1] << 3) + f[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];
for (int i = 1; i < num[m]; ++i) st[i] += tn[m - 1];
for (int i = 0; i < 10; ++i)
st[i] += f[m - 1] * (num[m] - 1);
st[num[m]] += res + 1;
for (int i = m - 1; i; --i)
{
res -= num[i] * tn[i - 1];
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;
for (int i = 1; i < 15; ++i)
{
f[i] = (f[i - 1] << 3) + (f[i - 1] << 1) + tn[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;
}