跳到正文

题解

P12397 「FAOI-R9」函数大师 题解

HirasawaYuii约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年5月2日
收录
2025年12月12日
更新
2026年11月10日
篇幅
约 4 分钟
题目
P12397

版本

  1. v1当前

P12397 「FAOI-R9」函数大师 题解

题目链接

思路

s(x)s(x) 意为 xx 的各位数字之和,下文以“缩”代指此类操作。

Sk(x)S_k(x) 意为被缩了 kk 次后 xx 的各位数字之和。

fk(x)=∑i=0kSi(x)f_k(x) = \sum_{i=0}^{k}S_i(x) 。

由于 1≤m≤10181\le m\le 10^{18},所以 s(m)s(m) 最大值即为 9×18=1629\times18=162。

显然,mm 只能最多被缩 33 次。

例如当 m=199m=199 时:199→19→10→1199\to 19\to 10\to1。

引入一个概念,数根:一个正整数的各位数字相加,直到得到一个一位数。

当 k>2k>2 时,后面的 ∑i=3kSi(m)\sum_{i=3}^{k}S_i(m) 显然都为 mm 的数根。

可得出:fk(x)=S0(x)+S1(x)+S2(x)+S3(x)×(k−2)(k≥2)f_k(x)=S_0(x)+S_1(x)+S_2(x)+S_3(x)\times(k-2)\left( k\ge2\right)

将所有 Sk(x)S_k(x) 消掉,设 xx 的数根为 yy,可进一步得出:fk(x)=x+s(x)+s(s(x))+y×(k−2)(k≥2)f_k(x)=x+s(x)+s(s(x))+y\times(k-2) \left( k\ge2\right)

代入 m=fk(x)m=f_k(x) 并移项后可得 x+s(x)+s(s(x))=m−y×(k−2)x+s(x)+s(s(x))=m-y\times(k-2)

由此,问题转化为了如何求该方程解的根。

从上面的概念和推导可得出,1≤y≤9,2≤s(x)+s(s(x))≤2001\le y\le 9,2\le s(x)+s(s(x))\le 200(此处 200200 为一个粗略值,大致是通过 162+9=171162+9=171 类似的操作得出)。

观察到数据范围很小,可以用枚举来解决。

这里选择枚举 yy,得出每一个 t=m−y×(k−2)t=m-y\times(k-2) 后再枚举 x∈[t−200,t]x\in[t-200,t]​ 并代入尝试,若相等即为一解。

这里还需要注意枚举 xx 的原根须和当前 yy 相等,具体处理方式可看代码。

最后统计解的个数即可。

此外,还需处理 k=0k=0 与 k=1k=1 的情况。k=0k=0 显然直接输出 1,k=1k=1 也可通过类似 k≥2k\ge2​ 的情况枚举即可]。

代码

C++
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define mst(x, y) memset(x, y, sizeof(x))
#define pii pair<ll, ll>
#define fi first
#define se second
#define mp(x, y) make_pair(x, y)

ll read(){ll x = 0, f = 1;char c = getchar();while(c < '0' || c > '9'){if(c == '-') f = -1;c = getchar();}while(c >= '0' && c <= '9'){x = 10*x+c-'0';c = getchar();}return f*x;}
void writ(ll x){if(x < 0){putchar('-');x = -x;}if(x > 9) writ(x/10);putchar(x%10 | 0x30);return;}
void write(ll x){writ(x);puts("");}
void wr(ll x){writ(x);putchar(' ');}
// const ll N = , inf = 0x3f3f3f3f;

ll k, m, ans;
ll s(ll x){
	ll res = 0;
	while(x){
		res += x%10;
		x /= 10;
	}
	return res;
}
void init(){
	m = read(), ans = 0;
}
void solve(){
	init();
	if(k == 0){
		write(1);
	}
	else if(k == 1){
		for(ll x = max(1ll, m-200);x <= m;x++){
			if(x+s(x) == m){
				ans++;
			}
		}
		write(ans);
	}
	else{
		for(ll y = 1;y <= 9;y++){
			ll t = m-y*(k-2), x = max(1ll, t-200);
			x = x+(y-x%9+9)%9;
			for(;x <= t;x += 9){
				if(x+s(x)+s(s(x)) == t){
					ans++;
				}
			}
		}
		write(ans);
	}
}

signed main(){
	ll T = read();
	k = read();
	while(T--) solve();
	return 0; 
}
原文