#include <iostream>
#include <vector>
#include <set>
using namespace std;
#define MAXN 510
struct Edge {
int next;
int cost;
Edge(int nn, int cc) {
next = nn;
cost = cc;
}
};
vector<Edge> graph[MAXN];
int weight[MAXN];
int d[MAXN], w[MAXN];
set<int> pre[MAXN];
int num[MAXN];
bool Bellman_Ford(int n, int c1) {
for (int i = 0; i < n; i++) {
d[i] = 1 << 30;
w[i] = 0;
num[i] = 0;
}
d[c1] = 0;
w[c1] = weight[c1];
num[c1] = 1;
for (int i = 1; i < n; i++) { //n - 1轮
for (int j = 0; j < n; j++) { //每轮遍历所有边
for (int k = 0; k < graph[j].size(); k++) {
int next = graph[j][k].next;
int cost = graph[j][k].cost;
if (d[next] > d[j] + cost) {
d[next] = d[j] + cost;
w[next] = w[j] + weight[next];
num[next] = num[j];
pre[next].clear();
pre[next].insert(j);
}
else if (d[next] == d[j] + cost) {
if (w[next] < w[j] + weight[next])
w[next] = w[j] + weight[next];
if (pre[next].find(j) == pre[next].end()) {
pre[next].insert(j);
num[next] += num[j];
}
}
}
}
}
for (int j = 0; j < n; j++) { //判断负环
for (int k = 0; k < graph[j].size(); k++) {
int next = graph[j][k].next;
int cost = graph[j][k].cost;
if (d[next] > d[j] + cost)
return false;
}
}
return true;
}
参考
《算法笔记》(胡凡)