单源有向最短路之spfa,可解决负环

本文介绍了一种基于图的最短路径算法——SPFA(Shortest Path Faster Algorithm)。该算法通过广度优先搜索的方式求解带权有向图中从源点到其他各点的最短路径。代码实现了SPFA算法的具体步骤,包括构建图、进行广度优先搜索并更新最短距离等过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
using namespace std;
const int maxn = 2e5 + 5;
int ver[maxn], edge[maxn], Next[maxn], head[maxn], d[maxn];
int tot, n, m;
bool v[maxn];
void add(int x, int y, int z) {
	ver[++tot] = y;
	edge[tot] = z;
	Next[tot] = head[x];
	head[x] = tot;
}

queue <int>q;
void spfa() {
	memset(v, 0, sizeof v);
	memset(d, 0x3f, sizeof d);
	d[1] = 0; v[1] = 1;
	
	q.push(1);
	while (q.size()) {
		int x = q.front(); q.pop();
		v[x] = 0;
		for (int i = head[x]; i; i = Next[i]) {
			int y = ver[i], z = edge[i];
			if (d[y] > d[x] + z) {
				d[y] = d[x] + z;
				if (!v[y]) q.push(y), v[y] = 1;
			}
		}
		
	}
}

int main() {
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int a, b, c; cin >> a >> b >> c;
		add(a, b, c);
	}

	spfa();
	for (int i = 1; i <= n; i++) cout << d[i] << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值