必要的准备
- 有向无环图才有拓扑排序。问题,如果判断一个有向图是否有环?点这里
- 拓扑排序的背后是约束关系,优先调度的问题首先被考虑。简单的,你应该先学习十进制数字再研究数论。问题,如何得到拓扑排序呢?点这里
拓扑排序API
TopologicalSort(Digraph G)
构造函数
bool isDAG()
是有向无环图么
stack<int>* order()
拓扑有序的节点
代码
#pragma once
#include"DirectedCycle.h"
#include"DepthFirstOrder.h"
class TopologicalSort
{
public:
TopologicalSort(Digraph& G);
bool isDAG() {
return !m_order->empty(); }
stack<int>* order() {
return m_order; }
private:
stack<int>* m_order=nullptr;
};
void testTopSort();
#include "TopologicalSort.h"
TopologicalSort::TopologicalSort(Digraph& G)
{
DirectedCycle cycleFinder(G);
if (!cycleFinder.hasCycle()) {
DepthFirstOrder* dfO=new DepthFirstOrder(G);
m_order=dfO->getRePost();
}
}
void testTopSort() {
Digraph G("tinyDAG.txt");
TopologicalSort topS(G);
out(topS.isDAG()), hh;
stack<int>* stk = topS.order();
while (!stk->empty()) {
int x = stk->top();
out(x);
stk->pop();
}
hh;
}
tinyDAG.txt
13
15
2 3
0 6
0 1
2 0
11 12
9 12
9 10
9 11
3 5
8 7
5 4
0 5
6 4
6 9
7 6