ABC 208 E - Digit Products

E - Digit Products

数位dp

因为只能由 1~9 相乘而来,所以 \(mul=2^a*3^b*5^c*7^d\), \(d<=c<=b<=a<=log_2k\), 所以最多 \(log^4k\) 种乘积,总复杂度为 \(O(log^4k*logn)\)

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <map>
using namespace std;
#define endl "\n"

typedef long long ll;
typedef pair<int, int> PII;

const int N = 20;
int pos;
int bound[N];
ll n, k;
//用map存第四维(乘积),因为乘积可能很大,但个数并不多(只能由2,3,5,7 四个质数相乘而来)
map<ll, ll> f[N][2][2];

ll dfs(int pos, ll mul, bool limit, bool zero)
{
	if (pos <= 0)
		return !zero && mul <= k;
	if (f[pos][limit][zero].count(mul))
		return f[pos][limit][zero][mul];
	int maxn = limit ? bound[pos] : 9;
	ll now = 0;
	for (int i = 0; i <= maxn; i++)
	{
		//不能这样写,因为当前乘积如果大于k,但之后 *0 后就满足条件了,要在递归出口判断
		// if (mul * i > k)
		// 	continue;
		if (zero && i == 0)
			now += dfs(pos - 1, mul, limit && i == bound[pos], true);
		else
			now += dfs(pos - 1, mul * i, limit && i == bound[pos], false);
	}
	if (limit)
		return now;
	return f[pos][limit][zero][mul] = now;
}
ll solve(ll x)
{
	pos = 0;
	do
	{
		bound[++pos] = x % 10;
		x /= 10;
	}while(x);
	return dfs(pos, 1, true, true);
}
int main()
{
	ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
	cin >> n >> k;
	cout << solve(n) << endl;
    return 0;
}
posted @ 2022-06-07 13:01  hzy0227  阅读(35)  评论(0编辑  收藏  举报