求一个有向无环图的拓扑序列c++
时间: 2024-02-03 20:03:58 浏览: 29
求一个有向无环图的拓扑序列的C++实现可以使用拓扑排序算法。具体步骤如下:
1. 扫描所有顶点,将入度为0的顶点加入队列。
2. 取出队首元素,输出该元素,并将该元素的所有出边的指向顶点的入度减1。
3. 如果某个顶点的入度减为0,则将该顶点加入队列。
4. 重复步骤2和3,直到队列为空。
以下是C++代码实现:
```c++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> topoSort(vector<vector<int>>& graph) {
int n = graph.size();
vector<int> inDegree(n, 0);
for (int i = 0; i < n; i++) {
for (int j = 0; j < graph[i].size(); j++) {
inDegree[graph[i][j]]++;
}
}
queue<int> q;
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
vector<int> res;
while (!q.empty()) {
int u = q.front();
q.pop();
res.push_back(u);
for (int i = 0; i < graph[u].size(); i++) {
int v = graph[u][i];
inDegree[v]--;
if (inDegree[v] == 0) {
q.push(v);
}
}
}
return res;
}
int main() {
vector<vector<int>> graph = {{1, 2}, {3}, {3}, {4, 5}, {5}, {}};
vector<int> res = topoSort(graph);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl;
return 0;
}
```