洛谷 #3020. 包快递Package Delivery

本文深入探讨了SPFA(Shortest Path Faster Algorithm)算法,一种用于求解带负权边的最短路径问题的有效算法。通过具体实例,详细解析了SPFA算法的工作原理、数据结构设计与代码实现细节,特别关注于如何高效地处理大规模图数据。

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

题意

最短路

题解

SPFA

调试记录

#include <cstdio>
#include <cstring>
#include <queue>
#define maxn 50005

using namespace std;

struct node{
	int to, next, l;
}e[maxn << 1];
int head[maxn], tot = 0;
void addedge(int u, int v, int l){
	e[++tot].to = v, e[tot].next = head[u], e[tot].l = l;
	head[u] = tot;
}

int dis[maxn];
bool inq[maxn];
void SPFA(){
	memset(dis, 0x3f, sizeof dis);
	dis[1] = 0;
	queue <int> q; while (!q.empty()) q.pop();
	q.push(1);
	inq[1] = true;
	
	while (!q.empty()){
		int cur = q.front(); inq[cur] = false; q.pop();
		
		for (int i = head[cur]; i; i = e[i].next){
			if (dis[e[i].to] > dis[cur] + e[i].l){
				dis[e[i].to] = dis[cur] + e[i].l;
				if (!inq[e[i].to]){
					q.push(e[i].to);
					inq[e[i].to] = true;
				}
			}
		}
	}
}

int n, m;
int main(){
	scanf("%d%d", &n, &m);
	
	for (int u, v, l, i = 1; i <= m; i++){
		scanf("%d%d%d", &u, &v, &l);
		addedge(u, v, l);
		addedge(v, u, l);
	}
	
	SPFA();
	printf("%d\n", dis[n]);
	
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值