单源最短路径Bellman_Ford, 边带负权值, 最短路径条数 c++模板

#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;
}

参考

《算法笔记》(胡凡)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值