跳到正文

题解

题解:P1001 A+B Problem

Deltary_约 5 分钟
原文
文章信息与版本

文章信息

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

版本

  1. v2当前
  2. v1

题意

给定 nn 个整数 a1,a2,⋯ ,ana_1, a_2 , \cdots , a_n ,其中 n=2n = 2,求 ∑i=1n\sum_{i = 1}^{n} 的值。

思路

看到这种数学题,第一眼反应是看模数,但这道题并没有要求对某个数取模。注意到到 ai∈[−109,109]a_i \in [-10^9, 10^9],则 ∑i=1n∈[−2×109,2×109]\sum_{i = 1}^{n} \in [-2 \times 10^9, 2 \times 10^9] ,使用 C/C++ 中的 int 也不会爆数据范围。看到区间求和可以想到从前缀和、树状数组到线段树、主席树的一系列算法。而本题不存在修改,考虑到常数很小,用以上每一种均可。

鉴于其他算法都有前人写过了,就来尝试用前缀和来实现。这里介绍一种没什么人用的写法,使用 C++ 标准库 <numeric> 中的 std::partial_sum 函数。

C++
template< class InputIt, class OutputIt >
OutputIt partial_sum( InputIt first, InputIt last,
                      OutputIt result );

std::partial_sum 将 [first,last)[\text{first}, \text{last}) 中的每一个数处理前缀和,并放在前缀和数组 result 中。需要注意的是 result 的大小一定要足够。最终输出前缀和数组的最后一项即可。例子如下(实际为 0-index,为了便于理解使用 1-index):

ii12345
aia_i12114514191981039393939
resultiresult_i13114517203432741428266

std::partial_sum 也可以重载加法运算,使用方法如下,在此不再赘述。

C++
template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator partial_sum (InputIterator first,
                            InputIterator last,
                            OutputIterator result,
                            BinaryOperation binary_op);

代码

C++
#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】求区间和 。

代码:

C++
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;
}
原文