代码如下:
#include <iostream>
#include <stack>
using namespace std;
const int N = 100;typedef struct Node
{int adj;int w;Node *next;}Node;typedef struct VNode
{int in;int v;Node *first;VNode(){first = nullptr;}
}VNode;class AOE
{
private:VNode adjList[N];int vn;int en;int tpord[N];int ve[N];int vl[N];bool coll[N];int path[N];bool vis[N];
public:AOE(){memset(ve, 0, sizeof(ve));memset(vl, 0, sizeof(vl));}void buildAOE(){int n, m;cin >> n >> m;vn = n;en = m;for (int i = 0; i < vn; i++){cin>>adjList[i].v;}for (int i = 0; i < en; i++){int x, y, w;cin >> x >> y >> w;Node *s = new Node;s->adj = y;s->w = w;s->next = adjList[x].first;adjList[x].first = s;}}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 toptpord(){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();tpord[cnt++] = xx;n--;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->w > ve[yy]){ve[yy] = ve[xx] + p->w;}}}if (!n){return true;}else{return false;}}bool criticPath(){if (!toptpord()) return false;for (int i = 0; i < vn; i++){vl[i] = ve[vn - 1];}for (int i = vn - 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->w < vl[xx]){vl[xx] = vl[yy] - p->w;}}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->w;if (e == l){coll[i] = coll[k] = true;}}}}return true;}void freeTime()//求机动时间{for (int i = 0; i < vn; i++){int xx = i;for (Node *p = adjList[i].first; p; p = p->next){int yy = p->adj;if (vl[yy] - ve[xx] - p->w > 0){cout << "yy = "<<yy<<" vl[yy] = " << vl[yy] <<" xx = "<<xx<< " ve[xx] = " << ve[xx] << " p->w = " << p->w << endl;cout << xx << " " << yy <<" "<< vl[yy] - ve[xx] - p->w<< endl;}}}cout << endl;}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->w);vis[k] = false;}}}void printPath(){for (int i = 0; i < vn; i++) vis[i] = false;vis[0] = true;dfs(0, 0, 0);}};int main()
{AOE g;g.buildAOE();g.criticPath();g.printPath();g.freeTime();return 0;
}
测试如下: