关键路劲算法c++实现
时间: 2023-12-10 12:04:07 浏览: 66
以下是关键路径算法的C++实现,其中包括了关键路径算法的主要步骤和数据结构:
```c++
#include <iostream>
#include <vector>
#include <queue>
#include <cstring>
using namespace std;
const int MAXN = 1005;
const int INF = 0x3f3f3f3f;
struct Edge {
int to, w;
Edge(int to, int w) : to(to), w(w) {}
};
vector<Edge> G[MAXN];
int inDegree[MAXN], earliest[MAXN], latest[MAXN];
bool vis[MAXN];
void init(int n) {
memset(inDegree, 0, sizeof(inDegree));
memset(earliest, 0, sizeof(earliest));
memset(latest, INF, sizeof(latest));
memset(vis, false, sizeof(vis));
for (int i = 0; i <= n; i++) {
G[i].clear();
}
}
void addEdge(int u, int v, int w) {
G[u].push_back(Edge(v, w));
inDegree[v]++;
}
bool topologicalSort(int n) {
queue<int> q;
for (int i = 1; i <= n; i++) {
if (inDegree[i] == 0) {
q.push(i);
vis[i] = true;
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].to;
int w = G[u][i].w;
inDegree[v]--;
if (inDegree[v] == 0) {
q.push(v);
vis[v] = true;
}
earliest[v] = max(earliest[v], earliest[u] + w);
}
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
return false;
}
}
return true;
}
void calcLatest(int n) {
queue<int> q;
for (int i = 1; i <= n; i++) {
if (inDegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i].to;
int w = G[u][i].w;
inDegree[v]--;
if (inDegree[v] == 0) {
q.push(v);
}
latest[u] = min(latest[u], latest[v] - w);
}
}
}
int main() {
int n, m;
cin >> n >> m;
init(n);
for (int i = 0; i < m; i++) {
int u, v, w;
cin >> u >> v >> w;
addEdge(u, v, w);
}
if (!topologicalSort(n)) {
cout << "No solution" << endl;
return 0;
}
int ans = 0;
for (int i = 1; i <= n; i++) {
ans = max(ans, earliest[i]);
}
cout << ans << endl;
calcLatest(n);
for (int i = 1; i <= n; i++) {
for (int j = 0; j < G[i].size(); j++) {
int v = G[i][j].to;
int w = G[i][j].w;
int e = earliest[i], l = latest[v] - w;
if (e == l) {
cout << i << "->" << v << endl;
}
}
}
return 0;
}
```
阅读全文