拓扑排序
有向无环图(Directed Acyclic Graph), 对于图G中的任意顶点的线性序列进行排序,使得图中任意一堆顶点u和v,若存在边<u, v> \(\in\)E(G), 则u在线性序列中出现在v之前。通常,这样的线性序列成为满足拓扑次序(Topological Order)的序列,简称拓扑序列。简单的说,由某个集合上的一个偏序得到该集合上的一个全序,这个操作称之为拓扑序列。
根据有向无环图的性质:
至少一个点入度为0 (假设不存在入度为0的点,那么对于n个点的图,如果我们一直遍历到第n+1个点,那么由抽屉原理前n+1个点存在重复遍历的)
对于拓扑序而言,所有入度为0的点都是拓扑序的初始点,那么我们从入度为0的点,开始将其出点的入度减1,若入度为0我们继续加入该序列,能够保证每次入队的点就是拓扑序。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
vector<int> a[N], res;
int en[N], n, m;
bool bfs() {
int cal = 0;
queue<int> q1;
for (int i = 1; i <= n; i ++){
if (!en[i]) q1.push(i), cal ++;
}
while (q1.size()) {
int t = q1.front(); q1.pop();
res.push_back(t);
for (auto &x: a[t]) {
if (!(--en[x])) {
q1.push(x), cal ++;
}
}
}
return cal == n;
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i ++) {
int x, y; cin >> x >> y;
a[x].push_back(y);
en[y] ++;
}
if (!bfs()) {
cout << -1;
} else {
for (int i = 0; i < res.size(); i ++) {
cout << res[i] << " \0"[i == (int) res.size() - 1];
}
}
}