若一个由图中所有点构成的序列 A 满足:对于图中的每条边 (x,y),x 在 A 中都出现在 y 之前,则称 A 是该图的一个拓扑序列。
拓扑排序主要是用于在一个DAG(有向无环图)中将所有的顶点按照依赖顺序关系构造成一个线性序列。拓扑排序后的线性序列不止有一种情况适合问题的解,即存在多解的情况。
思路:将图的入度为0的先输出(顺序随意),再将一个顶点所能到达的终点顶点逐一存入排序序列
代码:
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> topoSort(vector<vector<int>>& graph, vector<int>& inDegree){
vector<int> res;
queue<int> q;
int graphSize = graph.size();
for(int i = 1; i < graphSize; i++){
if(inDegree[i] == 0){
q.push(i);
}
}
while(q.size()){
int node = q.front();
q.pop();
res.push_back(node);
for(auto& i : graph[node]){
inDegree[i]--;
if(inDegree[i] == 0){
q.push(i);
}
}
}
if(res.size() != graphSize - 1){
res.clear();
}
return res;
}
int main(){
int n = 0, m = 0;
cin >> n >> m;
vector<vector<int>> graph(n + 1);
vector<int> inDegree(n + 1, 0);
for(int i = 0; i < m; i++){
int a = 0, b = 0;
cin >> a >> b;
graph[a].push_back(b);
inDegree[b]++;
}
vector<int> res;
res = topoSort(graph, inDegree);
if (res.empty()) {
cout << -1 << endl;
} else {
for (int i : res) {
cout << i << " ";
}
cout << endl;
}
}