关键路径与活动的完成有关,总之路径长度最长的路径叫关键路径。在AOE-网中只有一个入度为0的顶点(源点)和只有一个出度为零的顶点(汇点)。
图的存储结构为邻接表。
算法用到拓扑排序和逆拓扑排序。
算法如下:
(1) 算法用到的拓扑排序算法
void topoOrder(ALGraph *G, int ve[], int instack[])
{
int i, v, indegree[G->vexnum];
ArcNode *p;
int stack [G->vexnum], top = 0, intop = 0;
memset(indegree, 0, sizeof(indegree));
//memset(ve, 0, sizeof(int) * G->vexnum);
//find indegree
for (i = 0;i < G->vexnum;i++) {
for (p = G->vertices[i].firstarc;p;p = p->nextarc)
indegree[p->adjvex]++;
}
for (i = 0;i < G->vexnum;i++) {
//printf("%d ", indegree[i]);
if (indegree[i] == 0)
stack[top++] = i;
}
while (top > 0) {
v = stack[--top];
instack[intop++] = v;
//printf("V%d ", v + 1);
for (p = G->vertices[v].firstarc;p;p = p->nextarc) {
if (ve[v] + p->cost > ve[p->adjvex])
ve[p->adjvex] = ve[v] + p->cost;
if (--indegree[p->adjvex] == 0)
stack[top++] = p->adjvex;
}
}// while
printf("\n");
}
(2) 关键路径算法
void criticalPath(ALGraph *G)
{
int ve[G->vexnum], vl[G->vexnum], v;
int stack[G->vexnum + 1], top = 0;
ArcNode *p;
memset(ve, 0, sizeof ve);
topoOrder(G, ve, stack);
top = G->vexnum;
//memset(vl, ve[G->vexnum - 1], sizeof vl);
for (v = 0;v < G->vexnum;v++)
vl[v] = ve[G->vexnum - 1];
while (top > 0) {
v = stack[--top];
for (p = G->vertices[v].firstarc;p;p = p->nextarc)
if (vl[v] > vl[p->adjvex] - p->cost)
vl[v] = vl[p->adjvex] - p->cost;
} //while
printf("critical vertices in critical path:\n");
for (v = 0;v < G->vexnum;v++)
if (ve[v] == vl[v])
printf("V%d ", v + 1);
}
/**
9
1 2 6
1 3 4
1 4 5
2 5 1
3 5 1
4 6 2
5 7 9
5 8 7
6 8 4
7 9 2
8 9 4
0 0 0
*/
(3) 测试输出
(4)复杂度
算法的时间复杂度为O(n+e),n为顶点数,e为边数。