#include <iostream>
using namespace std;
#define MAXVERTEX 100
typedef int infotype;
#define NULL 0
struct ArcNode
{
int adjvex;
infotype *info;
ArcNode *nextarc;
};
struct VerNode
{
int vertex;
ArcNode *fistarc;
};
struct Algraph
{
VerNode vernode[MAXVERTEX];
int vernum, arcnum;
};
void CreateAlgraph(Algraph *G)
{
ArcNode *p;
int x, y, dut;
cout << "请输入图的顶点数和边数:" << endl;
cin >> G->vernum >> G->arcnum;
for(int i = 0; i < G->vernum; i++)
{
G->vernode[i].vertex = i;
G->vernode[i].fistarc = NULL;
}
for(int k = 0; k < G->arcnum; k++)
{
cout << "请输入第" << k + 1 << "条边所依附的顶点和此边的权值:" << endl;
cin >> x >> y >> dut;
p = (ArcNode *)malloc(sizeof(ArcNode));
p->adjvex = y;
p->info = (int *)malloc(sizeof(int));
*(p->info) = dut;
p->nextarc = G->vernode[x].fistarc;
G->vernode[x].fistarc = p;
}
}
void FindIndegree(Algraph *G, int indegree[])
{
ArcNode *p;
for(int n = 0; n < G->vernum; n++)
indegree[n] = 0;
for(int i = 0; i < G->vernum; i++)
for(int j = 0; j < G->vernum; j++)
if(i != j)
{
p = G->vernode[j].fistarc;
while(p != NULL)
if(p->adjvex == i)
{
++indegree[i];
p = p->nextarc;
}
else
p = p->nextarc;
}
}
void TopoloicalOrder(Algraph *G, int stackt[], int topt, int ve[])
{
int indegree[100];
int tops = -1;
int count = 0;
int stack[100];
int k;
ArcNode *p;
FindIndegree(G, indegree);
for(int i = 0; i < G->vernum; i++)
ve[i] = 0;
for( i = 0; i < G->vernum; i++)
if(!indegree[i])
{
tops++;
stack[tops] = i;
}
while(tops >= 0)
{
i = stack[tops];
tops--;
topt++;
stackt[topt] = i;
count++;
for(p = G->vernode[i].fistarc; p; p = p->nextarc)
{
k = p->adjvex;
if((ve[i] + * (p->info)) > ve[k])
{
ve[k] = ve[i] + *(p->info);
}
if((--indegree[k]) == 0)
{
tops++;
stack[tops] = k;
}
}
}
}
void CriticalPath(Algraph *G, int stackt[], int topt, int ve[], int vl[])
{
ArcNode *p;
int k, dut;
int ee, el;
int j;
char tag;
TopoloicalOrder(G, stackt, topt, ve);
for(int i = 0; i < G->vernum; i++)
vl[i] = ve[G->vernum - 1];
for (i = G->vernum - 2; i; i--)
{
p = G->vernode[i].fistarc;
while (p)
{
k = p->adjvex;
if( vl[k] - * (p->info) < vl[i])
vl[i] = vl[k] - *(p->info);
p = p->nextarc;
}
}
for(j = 0; j < G->vernum; j++)
for(p = G->vernode[j].fistarc; p != NULL; p = p->nextarc)
{
k = p->adjvex;
dut = *(p->info);
ee = ve[j];
el = vl[k] - dut;
tag = (ee == el) ? '*' : ' ';
cout << j << " " << k << " " << dut << " " << ee << " " << el << " " << tag << endl;
}
}
int main()
{
Algraph G;
int stackt[100];
int ve[100], vl[100];
int topt = -1;
CreateAlgraph(&G);
cout << "关键路径见下图(*):" << endl;
cout << "j k dut ee el tag" << endl;
CriticalPath(&G, stackt, topt, ve, vl);
return 0;
}
求图的关键路径
最新推荐文章于 2021-11-21 22:57:04 发布