题目:
Let's call some positive integer classy if its decimal representation contains no more than 3 non-zero digits.
For example, numbers 4, 200000, 10203 are classy and numbers 4231, 102306, 7277420000 are not.
You are given a segment [𝐿;𝑅]. Count the number of classy integers 𝑥 such that 𝐿≤𝑥≤𝑅.
Each testcase contains several segments, for each of them you are required to solve the problem separately.
Input
The first line contains a single integer 𝑇 (1≤𝑇≤10⁴) — the number of segments in a testcase.
Each of the next 𝑇 lines contains two integers 𝐿𝑖 and 𝑅𝑖 (1≤𝐿𝑖≤𝑅𝑖≤10¹⁸).
Output
Print 𝑇 lines — the 𝑖-th line should contain the number of classy integers on a segment [𝐿𝑖;𝑅𝑖].
翻译成人话就是
找到区间[L,R]中的数位上有不超过3个非0的数的个数。
思路:
对于数位DP问题来讲有一个常见的优化方式,就是借助前缀和
记忆化搜索的部分借鉴了AcWing大佬 凌乱之风 的文章 链接:https://www.acwing.com/blog/content/7944/
大家可以去看一下原文,对于模板的总结真的很到位
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long LL;
const int N = 25;
LL l, r;
int len, cnt, a[N], f[N][N], limit;
int T;
//f[i][j] 表示搜索到第i位数,非0个数为j的数字的个数
// pos: 表示当前dfs到数字的哪一位 cnt: 非0数字的个数 limit:是否具有限制
int dfs(int pos, int cnt, bool limit)
{
if (!pos)
return cnt <= 3; // 如果已经搜索到了第 0 位,则表示已经搜索完了
// 若满足条件则返回 1,答案+1,否则答案+0
if (!limit && f[pos][cnt] != -1)
return f[pos][cnt];
// 若当前数位没有限制,而且这种情况已经搜索过了
// 则直接返回之前存储的答案
int res = 0, up = limit ? a[pos] : 9; // up 表示上限数字,也就是这位数字最高不能超过多少
// 如果 limit 不为0 也就代表上一位或者更之前的数字没有到达上限值
// 也就意味着当前数字可以取得进制允许以内的所有数字且保证最后拼凑出来的数字不会超出 n
for (int i = 0; i <= up; i++)
{
if ((i == 1 && 3 == cnt)) continue;
res += dfs(pos - 1, cnt + (i != 0), limit && i == up);
}
return limit ? res : f[pos][cnt] = res;
}
LL cal(LL n)
{
memset(f, -1, sizeof f);
len = 0;
while (n) a[++len] = n % 10, n /= 10; //将每一位数字都加入数组中,方便处理
return dfs(len, 0, 1); // 从高位向低位进行搜索
}
int main()
{
cin >> T;
while (T--)
{
cin >> l >> r;
cout << cal(r) - cal(l - 1) << endl; //前缀和思想
}
return 0;
}