C++实现有向图最长路径
时间: 2023-08-12 18:15:27 浏览: 50
以下是C++实现有向图最长路径的示例代码,假设有n个结点和m条有向边:
```c++
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
const int M = 200010;
int n, m;
int h[N], e[M], ne[M], w[M], idx;
int dist[N], cnt[N];
bool st[N];
int q[N];
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
bool spfa() {
int hh = 0, tt = 0;
memset(dist, -0x3f, sizeof dist);
dist[1] = 0;
q[tt++] = 1;
st[1] = true;
while (hh != tt) {
int t = q[hh++];
if (hh == N) hh = 0;
st[t] = false;
for (int i = h[t]; ~i; i = ne[i]) {
int j = e[i];
if (dist[j] < dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if (cnt[j] >= n) return true; // 存在正环
if (!st[j]) {
q[tt++] = j;
if (tt == N) tt = 0;
st[j] = true;
}
}
}
}
return false;
}
int main() {
memset(h, -1, sizeof h);
scanf("%d%d", &n, &m);
while (m--) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
if (spfa()) puts("-1");
else printf("%d\n", dist[n]);
return 0;
}
```
其中,add函数用于添加一条有向边,spfa函数用于求解最长路径,即使用SPFA算法判断是否存在正环,如果存在则返回-1,否则返回n号结点的最长路径。