对于给定有向图,先进行拓扑处理,然后求出最长路径。
//寻找图的关键路径
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
using namespace std;
//最大边数,最大点数
const int Max_M=100100;
const int Max_N=50100;
struct Graph
{
int nodeNumber,Link[Max_N],number;
struct node
{
int vertex,weight,next;
} edge[Max_M];
void initGraph(int n=0)
{
number=n;
nodeNumber=0;
memset(Link,-1,sizeof(Link));
}
void addEdge(int vertex_x,int vertex_y,int weight)
{
edge[nodeNumber].vertex = vertex_y;
edge[nodeNumber].weight = weight;
edge[nodeNumber].next = Link[vertex_x];
Link[vertex_x] = nodeNumber;
nodeNumber++;
}
void eraseLink(int vertex)
{
Link[vertex] = -1;
}
} ;
// 求图的拓扑序
int topoOrder[Max_N],inDegree[Max_N];
bool topo(Graph &G, int *topoOrder)
{
memset(inDegree,0,sizeof(inDegree));
for (int i=0;i<G.number;i++)
{
for (int p=G.Link[i];p!=-1;p=G.edge[p].next)
inDegree[G.edge[p].vertex]++;
}
queue<int> que;
for (int i=0;i<G.number;i++)
if (inDegree[i] == 0)
que.push(i);
int cnt=0;
while (!que.empty())
{
int vertex = que.front();
topoOrder[cnt++] = vertex;
que.pop();
for (int p=G.Link[vertex];p!=-1;p=G.edge[p].next)
{
if (--inDegree[G.edge[p].vertex] == 0)
que.push( G.edge[p].vertex );
}
}
return cnt == G.number;
}
//求图的关键路径
//输出图的关键路径
int criPath[Max_N];
void findPrecusorNode(Graph &G, int vertex, int number)
{
criPath[number] = vertex;
//当前节点没有前驱节点,已经找到了一条关键路径
if (G.Link[vertex] == -1)
{
for (int i=number; i>0 ;i--)
printf("%d ",criPath[i]);
printf("%d\n",criPath[0]);
}
else
{
for (int p=G.Link[vertex]; p != -1; p=G.edge[p].next)
findPrecusorNode(G, G.edge[p].vertex, number+1);
}
}
int lastVis[Max_N];
Graph g;
void getCriticalPath(Graph &G, int *topoOrder)
{
memset(lastVis,0,sizeof(lastVis));
g.initGraph(G.number);
for (int i=0; i<G.number; i++)
{
for (int p=G.Link[i]; p != -1; p=G.edge[p].next)
{
if ( lastVis[ G.edge[p].vertex ] < lastVis[i] + G.edge[p].weight )
{
lastVis[ G.edge[p].vertex ] = lastVis[i] + G.edge[p].weight;
//更新前驱节点
g.eraseLink( G.edge[p].vertex);
g.addEdge(G.edge[p].vertex, i, G.edge[p].weight);
}
else
if ( lastVis[ G.edge[p].vertex ] == lastVis[i] + G.edge[p].weight )
g.addEdge(G.edge[p].vertex, i, G.edge[p].weight);
}
}
int Max_cost=0;
for (int i=0; i<G.number; i++)
Max_cost=max(Max_cost, lastVis[i]);
printf("关键路径长度为:%d\n",Max_cost);
for (int i=0; i<G.number; i++)
if (lastVis[i] == Max_cost)
{
// 输出关键路径
findPrecusorNode(g,i,0);
}
}
int main()
{
Graph G;
//给定10个节点
int n;
puts("请输入点的数目:");
scanf("%d",&n);
G.initGraph(n);
puts("请输入边的数目:");
int m,x,y,w;;
scanf("%d",&m);
printf("节点编号0 ~ %d\n",n-1);
puts("请输入边:(按格式 vertex_x vertex_y weight) ");
for (int i=1; i<=m; i++)
{
scanf("%d%d%d",&x,&y,&w);
G.addEdge(x,y,w);
}
if (topo(G, topoOrder))
getCriticalPath(G,topoOrder);
else
puts("图中存在环,故不存在关键路径");
return 0;
}