ATCoder 353 D - Another Sigma Problem

题目传送门

先吐槽一下,353中的C题,D题,E题出题套路都一样,除了 f(i,j)f(i,j) 不一样之外,都是让你求:

∑i=1N−1∑j=i+1N−1f(ai,aj)\sum_{i=1}^{N-1}\sum_{j=i+1}^{N-1}{f(a_i,a_j)}

我可没说用到的方法一样

思路

暴力做法

按照题意枚举即可。可以写一个函数 len 方便拼接整数。
温馨提示:不开long long见祖宗。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#define mod (long long)998244353 //宏定义要取的模
using namespace std;
long long n, a[200005], ans = 0;

long long len(long long x) {
long long ans = 1;
while (x != 0) {
x /= 10;
ans *= 10;
}
return ans;
} //计算 x 有多少位,返回 10 ^ {x的位数}

int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n - 1; i++) {
for (int j = i + 1; j <= n; j++) {
ans += (a[i] * len(a[i]) + a[j]) % mod;
//这一次 mod 是模 a[i] * len(a[i]) + a[j]
ans %= mod;
//这一次是模 ans 本身
}
}
cout << ans << endl;
return 0;
}

后缀和做法

前面的做法时间复杂度 O(n2)\mathcal O(n^2),然而 nn 最大是 2×1052 \times 10 ^ 5。显然,这种做法是不行的。

那应该如何优化呢?

结合样例分析:

1
2
3
3 14 15

考虑第二个数 1414,先看它前面的。

  • 与第一个数 33 组合,得到的答案是 3×100+14=3143 \times 100 + 14 = 314。
  • 假设还有一个数 123123,则得到的答案是 123×100+14=12314123 \times 100 + 14 = 12314。

也就是说,对于它前面的数 aia_i,答案为 ai×len(x)+xa_i \times len(x) + x。

在看他后面的:

  • 与第三个数发生组合,得到答案 15×100+14=151415 \times 100 + 14 = 1514
  • 假设还有一个数 123123,则得到的答案为 14×103+123=1231414 \times 10^3 + 123 = 12314

也就是说,对于它后面的数 aia_i,答案为 x×len(ai)+aix \times len(a_i) + a_i。

使用后缀和 sufisuf_i 记录第 ii 个数后面的 len(x)len(x) 的后缀和,加进 ansans 里即可。注意要取模

最终代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#define mod (long long)998244353
using namespace std;
long long n, a[200005], ans = 0;
long long suf[200005];

long long len(long long x) {
long long ans = 1;
while (x != 0) {
x /= 10;
ans *= 10;
}
return ans;
}

int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = n; i >= 1; i--) {
suf[i] = (suf[i + 1] + len(a[i])) % mod; //后缀和递推公式
//存的是 len(a[i]) 的后缀和。
}
for (int i = 1; i <= n; i++) {
ans += a[i] * (i - 1) % mod; //a[i] 在前面 i - 1 次的贡献。
ans %= mod;
ans += a[i] * suf[i + 1] % mod; //根据乘法分配律,应该乘以后面所有 len(a[i]) 的和。
//用提前准备好的后缀和就可以了。
ans %= mod;
}
cout << ans << endl;
return 0;
}


ATCoder 353 D - Another Sigma Problem
https://guaguaoier111.github.io/2024/05/12/ATCoder 353 D - Another Sigma Problem/
作者
Guagua111
发布于
2024年5月12日
许可协议