拓扑排序:
核心思路:
关键点就是将入度为0的点全部放入队列中,直到遍历完所有的点,如果队列中点的个数等于图中点的个数,
说明该图存在拓扑序列。
代码模板:
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
| int h[N], e[N], ne[N], idx; int d[N]; int res[N], cnt;
void add (int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx ++; }
bool topsort() { queue<int> q;
for (int i = 1; i <= n; i ++) { if (d[i] == 0) { q.push(i); } }
while (q.size()) { auto t = q.front(); res[ ++ cnt] = t; q.pop();
for (int i = h[t]; i != -1; i = ne[i]) { int j = e[i]; d[j] --; if (d[j] == 0) { q.push(j); } } } if (cnt == n) return true; return false; }
if (topsort()) { for (int i = 1; i <= cnt; i ++) printf("%d ", res[i]); } else cout << "-1" << endl;
|
注意:
(1)找到入度为0的点作根节点
(2)一定要将所有入度为0的点加入队列
(3)最后需要进行判断是否所有点都入队了,是则存在拓扑序,反之不存在。