题解:P13672 [GCPC 2023] German Conference for Public Counting
大意
给出一个数
解析
非优化思路
我们可以想出一个最朴素的思路:
- 枚举
n 到0 之间的数; - 统计每个数中
0 到9 最多出现次数的和; - 将现在的答案与之前存储的答案比较;
- 求和,输出。
很容易写出以下代码:
#include <bits/stdc++.h>
using namespace std;
int ans[10] = {1}, cnt[10];
int main() {
int n, sum = 0;
cin >> n;
for (int i = 1; i <= n; i++) {
int x = i;
memset(cnt, 0, sizeof(cnt));
while (x) {
cnt[x % 10]++;
x /= 10;
}
for (int j = 0; j <= 9; j++)
ans[j] = max(cnt[j], ans[j]);
}
for (int i = 0; i <= 9; i++)
sum += ans[i];
cout << sum;
return 0;
}
但是,超时了……
时间复杂度
为什么呢?我们可以计算一下它的时间复杂度——光枚举
因此,我们需要更优的思路。
优化思路
对于 1 到 9
我们仔细想想:假设一个数为
那这个问题和本题有什么关系呢?我们可以构造填满后的数,例如
对于 0
发现了吗?在
时间复杂度
时间复杂度:与
过了。记得开 long long, 因为 while 循环,此时这个数超过了 int 类型的最大值
代码
#include <bits/stdc++.h>
#define int long long
using namespace std;
signed main() {
int n, ans = 0;
cin >> n;
for (int i = 1; i <= 9; i++) {
int x = i; //防止 i 值发生变化。
while (x <= n) {
ans++;
x = x * 10 + i; //构造 1, 11, 111, 1111... 等数。
}
}
if (n < 100)
cout << ans + 1; //当 n 小于 100 时,仅有 1 个 0.
else {
int x = 0;
while (n) {
n /= 10;
x++;
}
cout << ans + x - 1; //否则统计 0 的数量,因为最高位不能为 0, 所以要 - 1.
}
return 0;
}