题意
给定 个整数 ,其中 ,求 的值。
思路
看到这种数学题,第一眼反应是看模数,但这道题并没有要求对某个数取模。注意到到 ,则 ,使用 C/C++ 中的 int 也不会爆数据范围。看到区间求和可以想到从前缀和、树状数组到线段树、主席树的一系列算法。而本题不存在修改,考虑到常数很小,用以上每一种均可。
鉴于其他算法都有前人写过了,就来尝试用前缀和来实现。这里介绍一种没什么人用的写法,使用 C++ 标准库 <numeric> 中的 std::partial_sum 函数。
template< class InputIt, class OutputIt >
OutputIt partial_sum( InputIt first, InputIt last,
OutputIt result );std::partial_sum 将 中的每一个数处理前缀和,并放在前缀和数组 result 中。需要注意的是 result 的大小一定要足够。最终输出前缀和数组的最后一项即可。例子如下(实际为 0-index,为了便于理解使用 1-index):
| 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|
| 1 | 2 | 114514 | 1919810 | 39393939 | |
| 1 | 3 | 114517 | 2034327 | 41428266 |
std::partial_sum 也可以重载加法运算,使用方法如下,在此不再赘述。
template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator partial_sum (InputIterator first,
InputIterator last,
OutputIterator result,
BinaryOperation binary_op);代码
#include <cstdio>
#include <cstdint>
#include <numeric>
#include <vector>
#define int int32_t
namespace IO {
inline int read() {
int x = 0, f = 1; char ch = getchar();
while(ch > '9' || ch < '0') {
if(ch == '-') f = -1;
ch = getchar();
}
while(ch >= '0' && ch <= '9') x = (x << 3) + (x << 1) + (ch - 48), ch = getchar();
return x * f;
}
void write(int x) {
if(x < 0) {
x = -x;
putchar('-');
}
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
}
std::vector <int> a;
std::vector <int> cnt;
int32_t main() {
int n = 2;
for(int i = 1; i <= n; i++) {
int tmp = IO::read();
a.push_back(tmp);
}
cnt.resize(a.size());
std::partial_sum(a.begin(), a.end(), cnt.begin());
IO::write(*cnt.rbegin());
return 0;
}拓展
这个使用函数也可以通过前缀和模板题 B3612 【深进1.例1】求区间和 。
代码:
std::vector <int> a;
std::vector <int> cnt;
int32_t main() {
int n = IO::read();
for(int i = 1; i <= n; i++) {
int tmp = IO::read();
a.push_back(tmp);
}
cnt.resize(a.size());
std::partial_sum(a.begin(), a.end(), cnt.begin());
int T = IO::read();
while(T--) {
int l = IO::read(), r = IO::read();
int ans = cnt[r - 1] - cnt[l - 2];
IO::write(ans); putchar('\n');
}
return 0;
}