「Note」拓扑排序

拓扑排序

拓扑排序是对一张 有向 并且 无环 的图进行遍历排序
如果在图中所有的节点构成的序列$A$中,对于每一条边$(x, y)$:$x$都出现在$y$的前面,则序列$A$就为这张图的拓扑序。

关于入度和出度

入度 :以节点$x$为终点的有向边的条数被称为$x$的入度。记作 $deg(x)$ .
出度 :以节点$x$为起点的有向边的条数被称为$x$的出度。
在这里插入图片描述
例如在此图中,节点3的入度就为2 ,节点4的入度也为2.

思想

不断选择图中入度为0的节点入队(如上图中的节点5、2、 1)。
再将$x$连向的节点的入度减一。

实现

1.建一个空的拓扑序列$A$。
2.预处理入度,将入度是0的节点全部入队。
3.取出队头,此时的对头$x$一定是入度为0的节点,所以$A[++ cnt] = x;$
4.对于此时的队头$x$,把所连的$y$的入度减一,即$deg[y] --;$
5.操作至队列为空,此时$A[]$则为这张图的拓扑排序。
6.在最后将$A[]$的长度检查以下,即看此时的$cnt$是否为图中的节点个数,如果少于了节点数,则说明图中有环。

图示

初始图
在这里插入图片描述
1.建立空序列
2.2.预处理入度,将入度是0的节点全部入队。
在这里插入图片描述
3.取出队头,此时的对头$x$一定是入度为0的节点,所以$A[++ cnt] = x;$
4.对于此时的队头$x$,把所连的$y$的入度减一,即$deg[y] --;$
5.操作至队列为空,此时$A[]$则为这张图的拓扑排序。

在这里插入图片描述
6.在最后将$A[]$的长度检查以下,即看此时的$cnt$是否为图中的节点个数,此时发现少了三个节点,所以图中含有环,即$(2, 4) (4, 6)(6, 2)$。

代码

本人太菜了,邻接表出了点玄学错误,就只能用矩阵。。。

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
#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

const int MAXN = 10005;
int n, m, cnt;
bool a[MAXN][MAXN];
int deg[MAXN], ans[MAXN];
queue<int> q;

void topsort(void) {
for (int i = 1; i <= n; i++)
if (deg[i] == 0)
q.push(i);
while (!q.empty()) {
const int u = q.front();
ans[++cnt] = u;
q.pop();
for (int i = 1; i <= n; i++)
if (a[u][i]) {
deg[i]--;
if (deg[i] == 0)
q.push(i);
}
}
}

int main() {
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
int x, y;
scanf("%d %d", &x, &y);
a[x][y] = 1;
deg[y]++;
}
topsort();
if (cnt < n) {
printf("no solution\n");
} else {
for (int i = 1; i <= cnt; i++) {
printf("%d ", ans[i]);
}
}
return 0;
}


The End
「Ô mon âme, n'aspire pas à la vie immortelle, mais épuise le champ du possible.」