C++实现AOE网中的关键路径算法(邻接表存储)
Posted Wecccccccc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++实现AOE网中的关键路径算法(邻接表存储)相关的知识,希望对你有一定的参考价值。
代码如下:
#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++)
{
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) cout << i << " -> " << k<<endl;
}
}
return true;
}
private:
Vnode adjlist[N];
int vn;
int en;
int tpord[N];
int ve[N];
int vl[N];
};
int main()
{
AoeGraph g;
g.createGraph();
g.Criticalpath();
return 0;
}
测试结果:
以上是关于C++实现AOE网中的关键路径算法(邻接表存储)的主要内容,如果未能解决你的问题,请参考以下文章