//—关键路径算法—
//关键路径:在边表示活动网(AOE-网)中,从开始点到完成点的最长路径。
//最早开始时间等于最迟开始时间的活动即为关键活动,e(i)==l(i)。
//而活动的最早开始时间等于弧尾结点表示的事件的最早发生时间,e(i)==ve(j)
//活动的最迟开始时间等于弧头结点表示的事件的最迟发生时间减去活动所需时间,l(i)==vl(k)-dut(<j,k>)
//1.先通过拓扑排序求出表示各事件的结点的拓扑序列
//2.按拓扑序列顺序从第一个结点开始按ve(j)==Max(ve(i)+dut(<i,j>))求出各结点的最早发生时间ve(i)
//3.按拓扑序列的逆顺序从最后一个结点开始根据vl(i)==Min(vl(j)-dut(<i,j>))往后递推求出各结点的最迟发生时间vl(i)
**
修正:以下为原来的代码,是错的,错的关键之处在于:算结点表示的事件的最迟发生时间时,未按拓扑逆序进行;而之所以在测试时未发现错误,是因为每次输入顶点都是按顺序输入的,导致顶点序列恰好是拓扑序列。正确代码附后面。
**
#include <stdio.h>
#include <stdlib.h>
#include "AdjacencyList.h"
typedef enum{FALSE,TRUE}Boolean;
typedef int Status;
//栈结构和方法
typedef struct
{
int st[MAX_VERTEX_NUM];
int top;
}Stack;
void StackPush(Stack *S,int u);
int StackPop(Stack *S);
Status TopologicalSort(ALGraph G,Stack *S);
void FindInDegree(ALGraph G,int *indegree);
Status CriticalPath(ALGraph G);
int VE[MAX_VERTEX_NUM],VL[MAX_VERTEX_NUM]; //VE[]为结点表示的事件的最早发生时间,VL[]为结点表示事件的最迟发生时间
int main()
{
ALGraph *G;
G=(ALGraph *)malloc(sizeof(ALGraph));
CreateGraph(G);
CriticalPath(*G);
return 0;
}
Status CriticalPath(ALGraph G)
{
Stack S;
S.top=0;
if(!TopologicalSort(G,&S))
return FALSE;
int i,k;
for(i=0;i<G.vexnum;i++)
VL[i]=VE[G.vexnum-1]; //初始化各个结点的最迟发生时间
ArcNode *p;
p=(ArcNode *)malloc(sizeof(ArcNode));
for(--i;i>=0;i--)
{
for(p=G.vertices[i].firstarc;p;p=p->nextarc)
{
k=p->adjvex;
if(VL[i]>VL[k]-*(p->info))
VL[i]=VL[k]-*(p->info);
}
}
printf("\n关键活动:");
for(i=0;i<G.vexnum;i++)
{
int k,ee,el;
for(p=G.vertices[i].firstarc;p;p=p->nextarc)
{
k=p->adjvex;
ee=VE[i];
el=VL[k]-*(p->info);
if(ee==el)
printf("%c---%c、 ",G.vertices[i].data,G.vertices[k].data);
}
}
printf("\n");
}
Status TopologicalSort(ALGraph G,Stack *S)
{
int i,count,*indegree,*ve; //indegree数组表示各个顶点的入度,索引表示顶点,值表示入度
indegree=(int *)malloc(sizeof(int)*G.vexnum);
for(i=0;i<G.vexnum;i++)
VE[i]=indegree[i]=0;
FindInDegree(G,indegree); //对各个顶点求入度
for(i=0;i<G.vexnum;i++)
if(!indegree[i])
StackPush(S,i); //将所有0入度的结点入栈
count=0;
printf("\n拓扑序列:");
while(S->top) //S.top>0则栈非空
{
int j;
j=StackPop(S); //从栈中取出一个0入度的结点
printf("%c ",G.vertices[j].data);
count++;
ArcNode *p;
p=(ArcNode *)malloc(sizeof(ArcNode));
for(p=G.vertices[j].firstarc;p;p=p->nextarc) //遍历该点的邻接点
{
int k;
k=p->adjvex;
if(VE[j]+*(p->info)>VE[k])
VE[k]=VE[j]+(*(p->info)); //在生成拓扑序列的同时,计算或更新各个结点事件的最早开始时间
if(!(--indegree[k])) //入度减-,如果为0,则入栈
StackPush(S,k);
}
}
if(count<G.vexnum)
{
printf("\n图中存在环!\n");
return FALSE;
}
else
return TRUE;
}
void FindInDegree(ALGraph G,int *indegree)
{
int i;
for(i=0;i<G.vexnum;i++)
{
ArcNode *t;
t=(ArcNode *)malloc(sizeof(ArcNode));
t=G.vertices[i].firstarc;
while(t)
{
int v;
v=t->adjvex;
indegree[v]++;
t=t->nextarc;
}
}
}
void StackPush(Stack *S,int u)
{
S->st[S->top++]=u;
}
int StackPop(Stack *S)
{
return S->st[--S->top];
}
正确代码:
#include <stdio.h>
#include <stdlib.h>
#include "AdjacencyList.h"
typedef enum{
FALSE,TRUE}Boolean;
typedef int Status;
//栈结构和方法
typedef struct
{
int st[MAX_VERTEX_NUM];
int top;
}Stack;
void StackPush(Stack *S,int u);
int StackPop(Stack *S);<