Topological sorting
拓扑排序:
拓扑排序要解决的问题是给一个有向无环图的所有节点排序。
拓扑排序的目标是将所有节点排序,使得排在前面的节点不能依赖于排在后面的节点。

DAG图

(有向无环图) Directed Acyclic Graph

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+5, M = 2e5+5;

int n, m, u, v, Cnt, head[N];
struct node
{
int nxt, to;
node(){}
node(int x, int v){ nxt = x, to = v; }
}e[M];
void Add_Edge(int u, int v)
{
e[Cnt] = node(head[u], v);
head[u] = Cnt++;
}
//BFS遍历实现拓扑排序(Kahn 算法)
//代码的核心是维持一个入度为0的顶点的集合。
int gin[N];
void toposort(void)
{
queue<int> S;
vector<int> L;
for(int i = 1; i<=n; ++i)
if(gin[i] == 0) S.push(i); //入度为0的点集合S
while(!S.empty())
{
int u = S.front();
S.pop();
L.push_back(u); //遍历顺序
for(int i = head[u]; ~i; i = e[i].nxt)
{
int v = e[i].to;
if((--gin[v]) == 0) S.push(v);
}
}
if(L.size() == n)
{
for(int i = 0; i<n; ++i) printf("%d ",L[i]);
puts("");
}
else puts("Error!");
}

int main()
{
cin>>n>>m;
memset(head, -1, sizeof(head));
for(;m;--m){
cin>>u>>v;
Add_Edge(u, v);
++gin[v];
}
toposort();
}


Thanks to SZUACM