> 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/graph-theory/union-find.md).

# 并查集

### 并查集的作用

维护若干个**不相交集合**，支持快速**合并**与**查询所属集合**。

### 基本实现

```cpp
int fa[N];

void init(int n) { for (int i = 1; i <= n; i++) fa[i] = i; }

int find(int x) {              // 路径压缩
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}

void unite(int a, int b) {     // 合并
    fa[find(a)] = find(b);
}
```

### 路径压缩

`find` 时把路径上的点直接连到根，后续查询接近 O(1)。

### 按秩合并（可选）

每次把小树接到大树下，避免退化：

```cpp
void unite(int a, int b) {
    int ra = find(a), rb = find(b);
    if (ra == rb) return;
    if (sz[ra] < sz[rb]) swap(ra, rb);
    fa[rb] = ra;
    sz[ra] += sz[rb];
}
```

两者结合，单次操作均摊接近 **O(α(n))**（反阿克曼函数，极小）。

### 应用

* 连通性问题、判断是否在同一集合
* Kruskal 最小生成树
* 判断无向图环


---

# 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/graph-theory/union-find.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.
