生活随笔
收集整理的這篇文章主要介紹了
AOV网拓扑排序(c/c++)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
拓撲排序
工程是否順序進行,流程是否合理,采用AOV網來表示,頂點用來表示工程(活動),弧表示工程間的順序關系。如a有一個指向b的弧,意味著a結束了b才能開始(a為弧尾,b為弧頭)
算法思路:1,在有向圖中找到無前驅(入度為0)的結點V,輸出。2,刪除V及以V為弧尾的弧。3,重復1,2,輸出全部結點/或者網中沒有無前驅的點(沒有入度為0的點,即存在環)
拓撲排序采用鄰接表較方便實現,下面給出以鄰接表存儲圖的算法:
void topoSort(aGraph
& G
)
{int* inDegree
= new int[G
.vexnum
];int i
, j
;arcNode
* temp
;for (i
= 0; i
< G
.vexnum
; i
++)inDegree
[i
] = 0;for (i
= 0; i
< G
.vexnum
; i
++)for (temp
= G
.vertices
[i
].firstArc
; temp
; temp
= temp
->nextArc
)inDegree
[temp
->adjvex
]++;int* stack
= new int[G
.vexnum
];int top
= -1;for (i
= 0; i
< G
.vexnum
;i
++)if (inDegree
[i
] == 0)stack
[++top
] = i
;int count
= 0;while (top
!= -1){j
= stack
[top
--];std
::cout
<< G
.vertices
[j
].data
<< ' ';++count
;for (temp
= G
.vertices
[j
].firstArc
; temp
; temp
= temp
->nextArc
){inDegree
[temp
->adjvex
]--;if (inDegree
[temp
->adjvex
]==0)stack
[++top
] = temp
->adjvex
;}}if (count
!= G
.vexnum
)std
::cout
<< "存在環!" << '\n';
}
完整示例
輸入為下面的有向圖,求它的拓撲排序:
#include<iostream>
#define maxSize 7
#define MAX 11
typedef struct arcNode
{int adjvex
;struct arcNode* nextArc
;
}arcNode
;
typedef struct
{char data
;arcNode
* firstArc
;
}adjList
;
typedef struct{int vexnum
, arcnum
;adjList vertices
[maxSize
];
}aGraph
;void topoSort(aGraph
& G
);
int main()
{using namespace std
;aGraph G
;G
.vexnum
= maxSize
;G
.arcnum
= MAX
;char vexData
[maxSize
] = { 'a', 'b', 'c', 'd', 'e','f','g' };int arcData
[MAX
][2] = { { 0, 2 }, { 0, 3 }, { 0, 4 }, { 1, 4 }, { 1, 3 }, { 2, 5 }, { 4, 3 },{ 3, 6 },{ 3, 5 }, { 4, 6 }, { 4, 5 } };int i
, j
;for (i
= 0; i
< G
.vexnum
; ++i
){G
.vertices
[i
].data
= vexData
[i
];G
.vertices
[i
].firstArc
= NULL;for (j
= 0; j
< G
.arcnum
;++j
)if (i
== arcData
[j
][0]){arcNode
* temp
= new arcNode
;temp
->adjvex
= arcData
[j
][1];temp
->nextArc
= G
.vertices
[i
].firstArc
;G
.vertices
[i
].firstArc
= temp
;}}cout
<< "拓撲排序: ";topoSort(G
);cout
<< endl
;arcNode
* temp
=NULL,* tt
=NULL;for (i
= 0; i
< G
.vexnum
; i
++){if (G
.vertices
[i
].firstArc
){temp
= G
.vertices
[i
].firstArc
;while (temp
){tt
= temp
->nextArc
;delete temp
;temp
= tt
;}}}return 0;
}void topoSort(aGraph
& G
)
{int* inDegree
= new int[G
.vexnum
];int i
, j
;arcNode
* temp
;for (i
= 0; i
< G
.vexnum
; i
++)inDegree
[i
] = 0;for (i
= 0; i
< G
.vexnum
; i
++)for (temp
= G
.vertices
[i
].firstArc
; temp
; temp
= temp
->nextArc
)inDegree
[temp
->adjvex
]++;int* stack
= new int[G
.vexnum
];int top
= -1;for (i
= 0; i
< G
.vexnum
;i
++)if (inDegree
[i
] == 0)stack
[++top
] = i
;int count
= 0;while (top
!= -1){j
= stack
[top
--];std
::cout
<< G
.vertices
[j
].data
<< ' ';++count
;for (temp
= G
.vertices
[j
].firstArc
; temp
; temp
= temp
->nextArc
){inDegree
[temp
->adjvex
]--;if (inDegree
[temp
->adjvex
]==0)stack
[++top
] = temp
->adjvex
;}}if (count
!= G
.vexnum
)std
::cout
<< "存在環!" << '\n';
}
輸出結果為:
總結
以上是生活随笔為你收集整理的AOV网拓扑排序(c/c++)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。