本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15797495.html

题目链接

题目

原题来自:ZJOI 2010
给定两个正整数 aabb,求在 [a,ba,b] 中的所有整数中,每个数码 (digitdigit) 各出现了多少次。

思路

首先在数位dp中,对于当前枚举的数,乘上后面的方案数。

那么后面的数如何多次计算呢?

我们发现这些数具有传递性,于是我们每次可以把后面的数传到前面来。

然后在每次记忆化搜索返回时,顺便加上后面的数即可。

总结

这道题总得来说还是不错的。

然而难点在于,当每次记忆化搜索返回时,后面的缺少统计了,于是我就尝试把他记起来。

然后又发现,在更后面的数又缺少统计,于是我发现这些统计的数由于记忆化搜索每次一样,所以具有传递性和普遍性,然后可以传递过来统计。

这也是数位dp的精妙之一。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// Problem: P2602 [ZJOI2010]数字计数
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P2602
// Memory Limit: 125 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define M
//#define mo
//#define N
int n, m, i, j, k;
int f[30][2][2], s[30][15][2][15], a[30], ans[15];
int x, y;

int dfs(int k, int p, int o)
{
if(k==0) return 1;
if(f[k][p][o]!=-1)
{
for(int i=0; i<=9; ++i) ans[i]+=s[k][p][o][i];
return f[k][p][o];
}
int i, j, q, z;
for(i=j=0; i<=9; ++i)
{
if(!p && i>a[k]) break;
q=dfs(k-1, p||(i<a[k]), o||i);
j+=q;
if(i||o) ans[i]+=q*m, s[k][p][o][i]+=q*m;
for(z=0; z<=9; ++z) s[k][p][o][i]+=s[k-1][p||(i<a[k])][o||i][z];
}
return f[k][p][o]=j;
}

void clac(int x)
{
memset(f, -1, sizeof(f));
memset(s, n=0, sizeof(s));
while(x) a[++n]=x%10, x/=10;
dfs(n, 0, 0);
}

signed main()
{
// freopen("tiaoshi.in", "r", stdin);
// freopen("tiaoshi.out", "w", stdout);
x=read(); y=read();
m=1; clac(y); m=-1; clac(x-1);
for(i=0; i<=9; ++i) printf("%lld ", ans[i]);
return 0;
}