代码如下:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
const int N = 10010;
using vnodeType = int;typedef struct Node
{int adj;int tw;//弧的时间权值Node *next;
}Node;typedef struct Vnode
{vnodeType v;//存储图中结点的信息int in;Node *first;}Vnode;class AoeGraph
{public:AoeGraph(){memset(adjlist, 0, sizeof(adjlist));memset(ve, 0, sizeof(ve));memset(tpord, 0, sizeof(tpord));memset(vl, 0, sizeof(vl));}void createGraph(){int n, m;cin >> n >> m;vn = n;en = m;for (int i = 0; i < vn; i++){cin >> adjlist[i].v;adjlist->first = nullptr;}for (int i = 0; i < m; i++){int x, y, w;cin >> x >> y >> w;Node *p = new Node;p->adj = y;p->tw = w;p->next = adjlist[x].first;adjlist[x].first = p;}}void findIn(){for (int i = 0; i < vn; i++){adjlist[i].in = 0;}for (int i = 0; i < vn; i++){for (Node *p = adjlist[i].first; p; p = p->next){adjlist[p->adj].in++;}}}bool TopOrder(){stack<int>s;findIn();for (int i = 0; i < vn; i++){if (adjlist[i].in == 0){s.push(i);}}int n = vn;int cnt = 0;while (!s.empty()){int xx = s.top();s.pop();n--;//tpord[cnt++] = adjlist[xx].v;tpord[cnt++] = xx;for (Node *p = adjlist[xx].first; p; p = p->next){int yy = p->adj;adjlist[yy].in--;if (adjlist[yy].in == 0){s.push(yy);}if (ve[xx] + p->tw > ve[yy]){ve[yy] = ve[xx] + p->tw;}}}if (!n) return true;else return false;}bool Criticalpath(){int cnt = vn;if (!TopOrder()) return false;for (int i = 0; i < vn; i++){vl[i] = ve[vn - 1];//初始化顶点事件的最迟发生时间}for (int i = cnt - 1; i >= 0; i--){int xx = tpord[i];for (Node *p = adjlist[xx].first; p; p = p->next){int yy = p->adj;if (vl[yy] - p->tw < vl[xx]){vl[xx] = vl[yy] - p->tw;}}}int e = 0;int l = 0;for (int i = 0; i < vn; i++) coll[i] = false;for (int i = 0; i < vn; i++){for (Node *p = adjlist[i].first; p; p = p->next){int k = p->adj;e = ve[i];l = vl[k] - p->tw;if (e == l) {coll[i] = coll[k] = true;}}}return true;}void dfs(int v,int cnt,int ans){path[cnt++] = v;if (v == vn - 1){cout << "value = " << ans << endl;for (int i = 0; i < cnt; i++){cout << path[i] << " ";}cout << endl;return;}for (Node *p = adjlist[v].first; p; p = p->next){int k = p->adj;if (!vis[k] && coll[k]){vis[k] = true;dfs(k, cnt, ans + p->tw);vis[k] = false;}}}void printPath(){for (int i = 0; i < vn; i++) vis[i] = false;vis[0] = true;dfs(0, 0, 0);}private:Vnode adjlist[N];int vn;int en;int tpord[N];int ve[N];int vl[N];bool coll[N];//标记关键路径的点bool vis[N];//标记是否访问过int path[N];//保存要输出的路径
};int main()
{AoeGraph g;g.createGraph();g.Criticalpath();g.printPath();return 0;
}
测试结果: