CodeForce 1036C Classy Numbers 数位DP 的记忆化搜索模板写法

题目:

Let's call some positive integer classy if its decimal representation contains no more than non-zero digits.

For example, numbers 420000010203 are classy and numbers 42311023067277420000 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问题来讲有一个常见的优化方式,就是借助前缀和   \sum_{i= 1}^{R} ans_{i} - \sum_{i = 1}^{L - 1} ans_{i}

记忆化搜索的部分借鉴了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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值