> 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/algorithm-techniques/difference-array.md).

# 差分（一维 / 二维）

### 差分的用途

差分用于**快速进行区间加 / 减**，与前缀和互为逆运算。

定义差分数组 `d[i] = a[i] - a[i-1]`。对区间 `[l, r]` 全部加 x，只需：

```cpp
d[l] += x;
d[r+1] -= x;
```

最后对 d 求前缀和即可还原 a。

```cpp
// 区间 [l, r] 加 x
d[l] += x; d[r + 1] -= x;

// 还原
for (int i = 1; i <= n; i++) {
    d[i] += d[i - 1];
    a[i] = d[i];
}
```

### 一维示例

原数组 a = \[0,0,0,0,0]，操作「2\~4 加 3」：

```
d[2] += 3, d[5] -= 3
前缀和后：0 3 3 3 3 0
```

### 二维差分

对矩形 `(x1,y1)~(x2,y2)` 加 x：

```cpp
d[x1][y1] += x;
d[x1][y2+1] -= x;
d[x2+1][y1] -= x;
d[x2+1][y2+1] += x;
// 还原时做二维前缀和
```

### 对比前缀和

|     | 前缀和     | 差分      |
| --- | ------- | ------- |
| 作用  | 区间求和    | 区间加减    |
| 预处理 | O(n)    | O(n)    |
| 操作  | 查询 O(1) | 修改 O(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/algorithm-techniques/difference-array.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.
