> 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/topological-sort.md).

# 拓扑排序与 DAG

### 有向无环图（DAG）

DAG 是没有环的有向图，很多“先后顺序”问题都能建成 DAG。

### 拓扑排序

把顶点排成线性序列，使每条边 `u → v` 中 u 都在 v 之前。

#### Kahn 算法（BFS，入度法）

```cpp
vector<int> adj[N];
int indeg[N], order[N], idx = 0;

void topo(int n) {
    queue<int> q;
    for (int i = 1; i <= n; i++)
        if (indeg[i] == 0) q.push(i);
    while (!q.empty()) {
        int u = q.front(); q.pop();
        order[idx++] = u;
        for (int v : adj[u])
            if (--indeg[v] == 0) q.push(v);
    }
    if (idx < n) cout << "存在环";   // 未输出全部，说明有环
}
```

#### DFS 法

对每个点 DFS，回溯时把点加入序列，最后翻转（需另检测环）。

### 应用

* 任务调度、课程安排（先修关系）
* 有向图判环
* 在 DAG 上做动态规划（如最长路）

### DAG 上的 DP

```cpp
dp[v] = max(dp[v], dp[u] + w);   // 按拓扑序递推
```


---

# 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/topological-sort.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.
