> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/data-structures/prefix-sum.md).

# 前缀和数组

### 什么是前缀和

前缀和用于**快速求区间和**。定义 `s[i]` 为数组前 i 个元素之和：

```cpp
s[i] = s[i - 1] + a[i];   // i 从 1 开始，s[0] = 0
```

### 区间和查询 O(1)

求 `a[l] + ... + a[r]`：

```cpp
sum = s[r] - s[l - 1];
```

```cpp
#include <iostream>
using namespace std;

int a[100005], s[100005];

int main() {
    int n, q;
    cin >> n >> q;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
        s[i] = s[i - 1] + a[i];      // 预处理前缀和
    }
    while (q--) {
        int l, r;
        cin >> l >> r;
        cout << s[r] - s[l - 1] << endl;   // O(1) 查询
    }
    return 0;
}
```

### 复杂度

* 预处理：O(n)
* 每次查询：O(1)
* 若不用前缀和，每次查询要 O(n)。

### 二维前缀和

```cpp
s[i][j] = s[i-1][j] + s[i][j-1] - s[i-1][j-1] + a[i][j];
// 求 (x1,y1) 到 (x2,y2) 的矩形和：
sum = s[x2][y2] - s[x1-1][y2] - s[x2][y1-1] + s[x1-1][y1-1];
```

### 与差分的关系

前缀和与**差分**是一对逆运算：前缀和用于快速**求和**，差分用于快速进行**区间加减**。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/data-structures/prefix-sum.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
