【CF 1538F Interesting Function】解题报告(结论题)
题意简述
给定 \(l,r\),不断 \(l\gets l+1\) 直到 \(l=r\),求过程中每一位变化次数之和。
例如 \(9\color{red}{39}+1=9\color{red}{40}\),这一过程中有两位变化。
题解
我们设 \(l\to r\) 的每一位变化次数之和为 \(f(l,r)\),类似于前缀和的思想,有 \(f(l,r)=f(0,r)-f(0,l)\)。
我们只需要求 \(f(0,x)\) 即可。
考虑个位在每次 \(+1\) 都会变,十位在 \(+10\) 之后才会变,以此类推,得到 \(f(0,x)=\sum\limits_{i=0}^9\lfloor\frac{x}{10^i}\rfloor\),可以求出最终答案。
参考代码
//By: Luogu@rui_er(122461)
#include <bits/stdc++.h>
#define rep(x,y,z) for(int x=y;x<=z;x++)
#define per(x,y,z) for(int x=y;x>=z;x--)
#define debug printf("Running %s on line %d...\n",__FUNCTION__,__LINE__)
using namespace std;
typedef long long ll;
int T, l, r;
template<typename T> void chkmin(T &x, T y) {if(x > y) x = y;}
template<typename T> void chkmax(T &x, T y) {if(x < y) x = y;}
int calc(int x) {
int ans = 0;
for(;x;x/=10) ans += x;
return ans;
}
int main() {
for(scanf("%d", &T);T;T--) {
scanf("%d%d", &l, &r);
printf("%d\n", calc(r)-calc(l));
}
return 0;
}