// Critical Path.cpp : Defines the entry point for the console application.
/*-----CODE FOR FUN---------------
-------CREATED BY Dream_Whui------
-------2015-2-15--------------------*/
//关键路径
#include "stdafx.h"
#include "graph.h"
#include <stack>
int indegree[MAX_VERTEX_NUM];
int ve[MAX_VERTEX_NUM];
int vl[MAX_VERTEX_NUM];
void FindInDegree(ALGraph G, int* indegree)//求各顶点的入度
{
int i,j;
ArcNode *p;
for(i=0; i<G.vexnum; i++)
{
p = G.vertices[i].firstarc;
while(p)
{
j = p->adjvex;
indegree[j]++;
p = p->nextarc;
}
}
}
int TopologicalOrder(ALGraph G, stack<int> &T)//有向图G采用邻接表的存储结构,求各顶点事件的最早发生时间ve
{ //T为拓扑序列顶点栈,S为零入度顶点栈
FindInDegree(G,indegree); //若G无回路,则用栈T返回G的一个拓扑序列
stack<int> S;
int i,j,k;
for(i=0; i<G.vexnum; i++)//入度为0的进栈
if(!indegree[i])
S.push(i);
int count = 0;
ArcNode *p;
while(!S.empty())
{
j = S.top();
S.pop();
T.push(j);//j号顶点的每个邻接点入栈并计数
++count;
for(p=G.vertices[j].firstarc; p!=NULL; p=p->nextarc)
{
k = p->adjvex;//对j号顶点的入度减1
if(--indegree[k]==0)//若入度为0,则进栈
S.push(k);
cout<<G.vertices[k].data<<"权值"<<*(p->info)<<endl;
if(ve[j] + *(p->info) > ve[k])
ve[k] = ve[j] + *(p->info);
}
}
if(count<G.vexnum)
return ERROR;
else
return OK;
}
int CriticalPath(ALGraph G)
{
stack<int> T;
if(!TopologicalOrder(G,T))
return ERROR;
int i,j,k,dut;
ArcNode *p;
for(i=0; i<G.vexnum; i++)
vl[i] = ve[G.vexnum-1];//初始化顶点事件的最迟发生时间
while(!T.empty()) //按拓扑逆序求各顶点的vl值
{
j = T.top();
T.pop();
for(p=G.vertices[j].firstarc; p!=NULL; p=p->nextarc)
{
k = p->adjvex;
dut = *(p->info);
if(vl[k]-dut < vl[j])
vl[j] = vl[k] - dut;
}
}
int ee,el;
for(i=0; i<G.vexnum; i++)
for(p=G.vertices[i].firstarc; p!=NULL; p=p->nextarc)
{
k = p->adjvex;
dut = *(p->info);
ee = ve[i];
el = vl[k] - dut;
if(ee == el)//输出关键活动
cout<<"("<<G.vertices[i].data<<"->"<<G.vertices[k].data<<","<<dut<<")";
}
}
int main(int argc, char* argv[])
{
ALGraph G;
CreateGraph(G);
CriticalPath(G);
//int i;
//for(i=0; i<G.vexnum; i++)
//{
// cout<<G.vertices[i].data<<"最早发生时间"<<ve[i]<<" ";
// cout<<G.vertices[i].data<<"最迟发生时间"<<vl[i]<<endl;
//}
return 0;
}