返回学习页
知识点指南

Prefix Sums

Prefix sums store cumulative totals. Once built, the sum of a range can be found by subtracting two stored totals.

什么时候使用

读题时可以留意这些信号。

  • The task asks for many interval totals.
  • You need repeated totals over consecutive positions.
  • The values are fixed while queries are answered.

常见错误

提交前可以检查这些小陷阱。

  • Mixing inclusive and exclusive endpoints.
  • Forgetting the initial zero.
  • Using prefix sums when values change and no update structure is provided.

怎么写成代码

把知识点翻译成变量、循环、判断和更新。

  • Make prefix[0] = 0.
  • Build prefix[i + 1] = prefix[i] + values[i].
  • For a half-open range [l, r), use prefix[r] - prefix[l].
  • For one-based inclusive ranges, convert endpoints carefully.

在 Block 题里长什么样

答题时通常会看到这些步骤被拆成代码块。

  1. 1Read N and values.
  2. 2Create prefix array of size N + 1.
  3. 3Loop through values to fill prefix.
  4. 4For each range, subtract prefix endpoints.
  5. 5Update or print the requested result.

题目里怎么出现

读题时先找这些信号,再决定答案区应该选哪些 blocks。

  • The story asks about total over a segment/window/range.
  • Many ranges are checked.
  • Recomputing each range from scratch would repeat work.

Range sum

一个小型模板,展示代码和 blocks 的对应关系。

C++

vector<int> prefix(N + 1, 0);
for (int i = 0; i < N; i++) {
    prefix[i + 1] = prefix[i] + values[i];
}
int sum = prefix[r] - prefix[l];

Python

prefix = [0] * (N + 1)
for i in range(N):
    prefix[i + 1] = prefix[i] + values[i]
sum_value = prefix[r] - prefix[l]

对应 block 顺序

  1. 1Read values.
  2. 2Create prefix array.
  3. 3Fill prefix cumulatively.
  4. 4Read/query range endpoints.
  5. 5Subtract prefix endpoints.
  6. 6Use or output the range total.

相关题目

用题库中的相关题目练习这个知识点。

1 道题

建议先练这道题

可以先从 Atlantis III: Twin Rivers 开始,再回到这里复盘知识点信号。

打开题目