跳到正文

题解

题解:P10985 [蓝桥杯 2023 国 Python A] 整数变换

喵仔牛奶约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年3月18日
篇幅
约 5 分钟
题目
P10985

版本

  1. v1当前

Description

给你一个 nn,每次减去数位和,求几次减完。

对于所有数据,n≤109n\le 10^{9}。

Solution

我看了一眼题,很快啊,啪地一下粘了个 CF331C3 的代码,直接跑到了最优解。

考虑 DP,想一想怎么设状态。考虑把一个数 nn 分成除最高位的部分 xx 和 n−xn-x。但是这样 nn 的最高位会产生影响,于是我们把最高也设进去。但是有了前面位的影响,可能会把 nn 减到 <0<0,于是再开一个 DP 数组存最后的 nn。

设 fx,nf_{x,n} 为前面的数位和为 xx 时使 n=0n=0 的最小步数,gx,ng_{x,n} 为减完后的 nn。

转移时,取出最大的 vv 使得 10v≤n10^v\le n,记 t=10vt=10^v,我们分成 n mod tn\bmod t 和 n−(n mod t)n-(n\bmod t) 两部分。于是我们分成了两个子问题。

但是如果 n mod t=0n\bmod t=0,那么就会无限循环。所以对于这种情况,我们手动操作一次,这样 n mod tn\bmod t 就不为 00 了。我们成功把原问题分成了 nn 更小的问题。

转移:

  • 若 n mod t=0n\bmod t=0:
    • 记 p=fx,n−x−⌊n/t⌋,q=gx,n−x−⌊n/t⌋p=f_{x,n-x-\lfloor n/t\rfloor},q=g_{x,n-x-\lfloor n/t\rfloor};
    • fx,n=p+1f_{x,n}=p+1,gx,n=qg_{x,n}=q。
  • 否则:
    • 记 p=fx+⌊n/t⌋,n mod t,q=gx+⌊n/t⌋,n mod tp=f_{x+\lfloor n/t\rfloor,n\bmod t},q=g_{x+\lfloor n/t\rfloor,n\bmod t};
    • fx,n=p+fx,n−(n mod t)+qf_{x,n}=p+f_{x,n-(n\bmod t)+q},gx,n=gx,n−(n mod t)+qg_{x,n}=g_{x,n-(n\bmod t)+q}。

还有边界情况:

  • 若 n=0n=0,fx,n=gx,n=0f_{x,n}=g_{x,n}=0。
  • 记 w(n)w(n) 是 nn 的数位和,若 n≤x+w(n)n\le x+w(n),fx,n=1f_{x,n}=1,gx,n=n−x−w(n)g_{x,n}=n-x-w(n)。

记搜实现即可。分析一下复杂度:

  • 每次的 nn,要么是原来的 nn 的后缀,要么是 999…99xy‾\overline{999\dots99xy}(若干个 99 加上最后 O(log⁡(∣Σ∣log⁡n))≈2\mathcal{O}(\log(\lvert\Sigma\rvert\log n))\approx 2 位)。所以 nn 只有 O(∣Σ∣log⁡2n)\mathcal{O}(\lvert\Sigma\rvert\log^2 n) 种(其中 Σ\Sigma 是字符集,本题中是 0∼90\sim 9)。
  • 而 xx 只有 max⁡w(n)≈O(∣Σ∣log⁡n)\max w(n)\approx\mathcal{O}(\lvert\Sigma\rvert\log n) 种,故总状态数为 O(∣Σ∣2log⁡3n)\mathcal{O}(\lvert\Sigma\rvert^2\log^3 n)。
  • 每次求出 tt 与 w(n)w(n) 需要 O(log⁡n)\mathcal{O}(\log n),不过这玩意可以轻松做到 O(1)\mathcal{O}(1)。
  • 总复杂度为 O(∣Σ∣2log⁡4n)\mathcal{O}(\lvert\Sigma\rvert^2\log^4 n),精细实现可以做到 O(∣Σ∣2log⁡3n)\mathcal{O}(\lvert\Sigma\rvert^2\log^3 n)。

Code

C++
#define REP(i, l, r) for (int i = (l); i <= (r); ++ i)
#define DEP(i, r, l) for (int i = (r); i >= (l); -- i)
#define fi first
#define se second
#define pb emplace_back
#define mems(x, v) memset((x), (v), sizeof(x))
#define SZ(x) (int)(x).size()
#define ALL(x) (x).begin(), (x).end()
using namespace std;
namespace Milkcat {
	typedef long long LL;
	typedef pair<LL, LL> pii;
	const int N = 1e6 + 5;
	LL n; unordered_map<LL, pii> f[101];
	LL calc(LL n) {
		LL x = 0;
		while (n) x += n % 10, n /= 10;
		return x;
	}
	pii dfs(LL x, LL n) {
		if (!n) return {0, 0};
		if (n <= x + calc(n)) return {1, n - x - calc(n)};
		if (f[x].count(n)) return f[x][n];
		LL t = 1; while (t <= n / 10) t *= 10;
		if (n % t == 0) {
			auto [p, q] = dfs(x, n - x - calc(n));
			return {p + 1, q};
		}
		auto [p, q] = dfs(x + n / t, n % t);
		auto [A, B] = dfs(x, n / t * t + q);
		return f[x][n] = {p + A, B};
	}
	int main() {
		cin >> n;
		cout << dfs(0, n).fi << '\n';
		return 0;
	}
}
原文