题目链接:

https://www.luogu.com.cn/problem/P2602
https://www.acwing.com/problem/content/340/

题目大意:

计算 \(a\)\(b\) 区间中每一个数码出现的次数。

思路:

记忆化搜索

#include <bits/stdc++.h>
using namespace std;
#define LL long long
const int N = 15;
LL dp[N][N], num[N];
LL dfs(int pos, LL sum, int limit, int zero, int d){
	/*
		pos 表示当前枚举到第几位
		sum 表示 d 出现的次数
		limit 为 1 表示枚举的数字有限制
		zero 为 1 表示有前导 0
		d 表示要计算出现次数的数
	*/
	if (pos == 0) return sum;
	if (!limit && !zero && dp[pos][sum] != -1) return dp[pos][sum];
	LL ans = 0;
	int up = (limit ? num[pos] : 9);
	for (int i = 0; i <= up; i ++ )
		ans += dfs(pos - 1, sum + ((!zero || i) && (i == d)), limit && (i == num[pos]), zero && (i == 0), d);
	if (!limit && !zero) dp[pos][sum] = ans;
	return ans;
}
LL solve(LL x, int d){
	memset(dp, -1, sizeof dp);
	int len = 0;
	while(x){
		num[++ len] = x % 10;
		x /= 10;
	}
	return dfs(len, 0, 1, 1, d);
}
int main(){
	ios::sync_with_stdio(false);cin.tie(0);
	LL a, b;
	cin >> a >> b;
	for (int i = 0; i <= 9; i ++ )
		cout << solve(b, i) - solve(a - 1, i) << " \n"[i == 9];
	return 0;
}

直接计算
举个例子,对于一个数 \(abcdefg\),计算 \(d\) 这一位上 \(x\) 出现的次数。
首先,分成两类。
小于 \(abcx000\) 的:
如果 \(x\) 大于 0 的,那有 \(abc\) * 1000 种,即前面为 \(abc\),后面是 000 到 999。
如果 \(x\) 等于 0 的,前面不能为 0,答案为 \((abc - 1) * 1000\) 种。
等于 \(abckkkk\) 的:
如果 \(x\) 等于 \(d\),那么后面可以从 000 到 \(efg\),总共 \(efg + 1\) 种。
如果 \(x\) 大于 \(d\),没有答案。
如果 \(x\) 小于 \(d\),有 1000 种,即这一位上为 \(x\),后面为 0 ~ 999。

#include <bits/stdc++.h>
using namespace std;
#define LL long long
LL a, b;
LL get(LL x){
	LL cnt = 0;
	while (x){
		cnt++;
		x /= 10;
	}
	return cnt;
}
LL count(LL n, LL x){
	LL ans = 0, len = get(n);
	for (int i = 1; i <= len; i ++ ){
		LL p = pow(10, i - 1), l = n / p / 10, k = n / p % 10, r = n % p;
		if (x) ans += l * p;
		else if (l) ans += (l - 1) * p;
		if (l || x){  //如果 l 和 x 都为 0,即有前导 0 的情况,是不可能的
			if (k > x) ans += p;
			else if (k == x) ans += r + 1;
		}
	}
	return ans;
}
int main(){
	cin >> a >> b;
	for (int i = 0; i <= 9; i ++ )
		cout << count(b, i) - count(a - 1, i) << " \n"[i == 9];
	return 0;
}

题目:

不要62:https://vjudge.net/problem/HDU-2089 (数字中不出现 4 或者 62)
windy数:https://www.luogu.com.cn/problem/P2657 (不出现前导零且相邻数之间差值 >= 2)

posted on 2022-04-18 15:54  Hamine  阅读(24)  评论(0编辑  收藏  举报