数位DP - AcWing 338 - 计数问题
注意前导0的影响
#include <bits/stdc++.h>
using namespace std;
int a, b;
int num[10];
int dp[10][10]; // 当前填位i,tar数已经出现的次数j
int dfs(int i, int j, int flag, int first, int tar){
if(!i) return j;
if(!flag && !first && dp[i][j] != -1) return dp[i][j];
int ans = 0;
int max_num = flag ? num[i] : 9;
for(int v = 0; v <= max_num; ++v){
ans += dfs(i-1, j + (!(first && (!v)) && (v==tar)), flag && (v==num[i]), first && (!v), tar);
}
if(!flag && !first) dp[i][j] = ans;
return ans;
}
void solve(int x, int y){
if(x > y) swap(x, y);
int ans[10];
num[0] = 0;
do{
num[++num[0]] = y % 10;
y /= 10;
}while(y);
for(int tar = 0; tar < 10; ++tar){
memset(dp, -1, sizeof dp);
ans[tar] = dfs(num[0], 0, 1, 1, tar) ;
}
--x;
num[0] = 0;
do{
num[++num[0]] = x % 10;
x /= 10;
}while(x);
for(int tar = 0; tar < 10; ++tar){
memset(dp, -1, sizeof dp);
ans[tar] -= dfs(num[0], 0, 1, 1, tar);
}
for(int i = 0; i < 10; ++i){
printf("%d ", ans[i]);
}
putchar('\n');
}
int main(){
while(scanf("%d%d", &a, &b) && (a || b)){
solve(a, b);
}
return 0;
}