2021-1拓撲排序 c++
阿新 • • 發佈:2021-02-01
必要的準備
拓撲排序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