(1) Directed Acyclic Graph 无环有向图
检测一个工程是否顺利进行
若以图中顶点表示活动,,有向边表示活动之间的优先关系,此图为AOV(Activity On Vertex network)
Vi -> Vj ,表示 Vi 是 Vj 的前趋,Vj 是 Vi 的后继
(2)对AOV排序,即拓扑排序,算法:
1.从AOV中选取无前趋的点(即入度为0的点)且输出
2.从网中删去该点,并且删除所有由该点发出的边
3.重复1,2,直到网中不存在无前趋的点
(3)结果
1. 网中无点,成功。
2.有点,说明网中有回路,排序失败。
(4)具体实现
#include <iostream>
using namespace std;
#define N 9
/* if (Vi -> Vj) matrix[i][j] = 1 */
int matrix[N][N]=
{
0,1,1,1,0,0,0,0,0,
0,0,0,0,1,0,0,0,0,
0,0,0,0,1,0,0,0,0,
0,0,0,0,0,1,0,0,0,
0,0,0,0,0,0,1,1,0,
0,0,0,0,0,0,0,1,0,
0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,0
};
int into[N]; // Vertex N 's indegrees
/* functions declaration */
void get_into_degree(int n);
void toposort(int n);
/* functions definition */
// in degrees
void get_into_degree(int n){
for(int j = 0; j < n; ++j){
into[j] = 0;
for(int i = 0; i < n; ++i)
if(matrix[i][j] == 1)
into[j]++;
}
}
// calculate and output
void toposort(int n){
//需要输出n个结点,排序结束
for(int i = 1; i <= n; ++i){
int j = 0;
// find the vertex which indegree is 0
while(j < n && into[j] != 0) j++;
// output the vertex
cout<<j + 1<<" ";
into[j] = N; // in order not to output the j again
// clear the Vertex's edge
for(int k = 0; k < n; ++k)
if(matrix[j][k] == 1)
into[k]--;
}
}
int main(){
get_into_degree(N);
toposort(N);
return 0;
}