1. 程式人生 > 其它 >2021-1拓撲排序 c++

2021-1拓撲排序 c++

技術標籤:日常練習c++拓撲排序

必要的準備

  • 有向無環圖才有拓撲排序。問題,如果判斷一個有向圖是否有環?點這裡
  • 拓撲排序的背後是約束關係,優先排程的問題首先被考慮。簡單的,你應該先學習十進位制數字再研究數論。問題,如何得到拓撲排序呢?點這裡

拓撲排序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