一,AOV网与拓扑序列
1,AOV(Activity On Vertex)网
设G是一个具有n个顶点的有向无环图,有向无环图通常用来表示活动之间的先后顺序。顶点表示活动,有向边表示活动之间的先后顺序。若活动 u 的完成是活动 v 可以开始的条件,则在顶点 u 与顶点 v 之间有一条边。若从顶点 u 到顶点 v 有一条有向路径,则 u 是 v 的前驱,v 是 u 的后继。这样的有向图称为AOV网。
2,拓扑序列
设G是一个具有n个顶点的有向无环图,图中的顶点序列v1、v2、...、vn,称为一个拓扑序列,当且仅当该顶点序列满足下面的条件,若vi, vj之间有边直接相连,则在序列中 vi 必须排在 vj 之前。
二,拓扑排序思想
在一个有向图中找一个拓扑序列的过程称为拓扑排序
1,从有向图中找一个没有前驱,即入度为0的顶点,输出这个顶点的编号。
2,从图中删去这个顶点,并且删除从该顶点出发的所有有向边。
3,重复上面两个过程,直到剩余的图中不存在没有前驱的顶点。
三,拓扑排序算法实现
#include <iostream>
using namespace std;
const int maxSize = 20;
/**
* 边节点
*/
struct ANode{
int vertex;
int value;
struct ANode *pNextANode;
};
/**
* 表头节点
*/
struct VNode{
char data;
int Count; //保存每个节点的入度值
ANode *pFirstANode;
};
/**
* 图的邻接矩阵数据结构
*/
struct AGraph{
VNode vertexArray[maxSize];
int n, e;
};
/**
* 创建图的邻接矩阵
*/
void createAdjacencyGraph(AGraph *g, int a[][maxSize], int n){
int i, j;
ANode *p;
g->e = 0;
g->n = n;
for(i = 0; i < n; i ++){
g->vertexArray[i].pFirstANode = NULL;
g->vertexArray[i].Count = 0;
}
for(i = 0; i < n; i ++){
for(j = 0; j < n; j ++){
if(a[i][j] != 0){
p = new ANode();
p->vertex = j;
p->value = a[i][j];
p->pNextANode = g->vertexArray[i].pFirstANode;
g->vertexArray[i].pFirstANode = p;
g->e ++;
g->vertexArray[j].Count ++;
}
}
}
}
/**
* 拓扑排序
*/
bool TopSort(AGraph *g, int Topsq[]){
int i, j, n = 0;
int st[maxSize], top = -1;
ANode *p;
for(i = 0; i < g->n; i ++){
if(g->vertexArray[i].Count == 0){
top ++;
st[top] = i;
}
while(top > -1){
i = st[top];
top --;
Topsq[n] = i;
n ++;
p = g->vertexArray[i].pFirstANode;
while(p != NULL){
j = p->vertex;
g->vertexArray[j].Count --;
if(g->vertexArray[j].Count == 0){
top ++;
st[top] = j;
}
p = p->pNextANode;
}
}
}
if(n < g->n){
return false;
} else {
return true;
}
}
int main()
{
int n = 6;
int a[maxSize][maxSize] = {
{0, 1, 1, 1, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0}
};
int res[maxSize];
AGraph g;
createAdjacencyGraph(&g, a, n);
TopSort(&g, res);
return 0;
}