拓撲排序的實現 TopoSort

2021-09-07 13:47:07 字數 2217 閱讀 9307

拓撲排序是求乙個aov網(頂點代表活動, 各條邊表示活動之間的率先關係的有向圖)中各活動的乙個拓撲序列的運算, 可用於測試aov

網路的可行性.

整個演算法包含三步:

1.計算每乙個頂點的入度, 存入indegree陣列中.

2.檢查indegree陣列中頂點的入度, 將入度為零的頂點進棧.

3.不斷從棧中彈出入度為0的頂點並輸出, 並將該頂點為尾的全部鄰接點的入度減1, 若此時某個鄰接點的入度為0, 便領其進棧. 反覆步驟

3, 直到棧為空時為止. 此時, 或者所有頂點都已列出, 或者因圖中包括有向迴路, 頂點未能所有列出.

實現**:

#include "iostream"

#include "cstdio"

#include "cstring"

#include "algorithm"

#include "queue"

#include "stack"

#include "cmath"

#include "utility"

#include "map"

#include "set"

#include "vector"

#include "list"

#include "string"

using namespace std;

typedef long long ll;

const int mod = 1e9 + 7;

const int inf = 0x3f3f3f3f;

enum resultcode ;

template struct enode

enode(int vertex, t weight, enode *nxt)

int adjvex;

t w;

enode *nxtarc;

/* data */

};template class graph

virtual resultcode insert(int u, int v, t &w) = 0;

virtual resultcode remove(int u, int v) = 0;

virtual bool exist(int u, int v) const = 0;

/* data */

};template class lgraph: public graph

void output();

protected:

enode**a;

int n, e;

/* data */

};template void lgraph::output()

cout << endl;

} cout << endl << endl;

}template lgraph::lgraph(int msize)

template lgraph::~lgraph()

} delete a;

}template bool lgraph::exist(int u, int v) const

template resultcode lgraph::insert(int u, int v, t &w)

template resultcode lgraph::remove(int u, int v)

if(!p) return notpresent;

if(q) q -> nxtarc = p -> nxtarc;

else a[u] = p -> nxtarc;

delete p;

e--;

return success;

}template class extlgraph: public lgraph

void toposort(int *order);

private:

void callindegree(int *indegree);

/* data */

};template void extlgraph::toposort(int *order)

for(int i = 0; i < lgraph::n; ++i)

}} }

}template void extlgraph::callindegree(int *indegree)

int main(int argc, char const *ar**)

拓撲排序toposort 模板

對乙個有向無環圖 directed acyclic graph簡稱dag g進行拓撲排序,是將g中所有頂點排成乙個 線性序列 拓撲排序方法如下 1 從有向圖中選擇乙個沒有前驅 即入度為0 的頂點並且輸出它.2 從網中刪去該頂點,並且刪去從該頂點發出的全部有向邊.3 重複上述兩步,直到剩餘的網中不再存...

拓撲排序的實現

看了拓撲排序 這裡走一遍拓撲排序的 以及運算結果 相關的 解釋 已經在程式中標明了 include include using namespace std const int max vertex num 30 最大結點數 stacks 定義棧 儲存度為0的頂點 typedef struct arc...

拓撲排序的演算法實現

找出乙個入度為 0 的頂點,通過遞迴的方式遍歷它所有可達的頂點,將其輸出到拓撲排序的結果序列中,對遍歷過的頂點做標記,避免其被重複訪問。迴圈執行上面的過程,直到所有的頂點都被輸出。public class topologicalsort adjacencylist dfs this.isvisite...