spfa求存在负权边的最短路

spfa是bellman——ford的队列优化版本,通过bfs:

优化的是dist[b] = min(dist[b], dist[a]+w)
因为只有dist[a]更新之后变小, dist[b]更新之后才有可能变小
需要st[i]数组,保证队列里面只有一个i;

给定一个 nn 个点 mm 条边的有向图,图中可能存在重边和自环, 边权可能为负数

请你求出 11 号点到 nn 号点的最短距离,如果无法从 11 号点走到 nn 号点,则输出 impossible

数据保证不存在负权回路。

输入格式

第一行包含整数 nn 和 mm。

接下来 mm 行每行包含三个整数 x,y,zx,y,z,表示存在一条从点 xx 到点 yy 的有向边,边长为 zz。

输出格式

输出一个整数,表示 11 号点到 nn 号点的最短距离。

如果路径不存在,则输出 impossible

数据范围

1≤n,m≤1051≤n,m≤105,
图中涉及边长绝对值均不超过 1000010000。

输入样例:

3 3
1 2 5
2 3 -3
1 3 4

输出样例:

2

 

#include <iostream>
#include <cstring>
#include <queue>

using namespace std;

const int N = 1e05+ 10;
int read(){
	int res = 0 , flag = 1 ;
	char c = getchar() ;
	while(!isdigit(c)){
		if(c == '-') flag = -1 ;
		c = getchar() ;
	}
	while(isdigit(c)){
		res = (res << 1) + (res << 3) + (c ^ 48) ;
		c = getchar() ;
	}
	return res * flag ; 
}

int ne[N], h[N], e[N], w[N], idx;
bool st[N];
int dist[N];
int n, m;

queue<int> q;
void add(int a, int b, int c) {
	e[idx] = b;
	ne[idx] = h[a];
	w[idx] = c;
	h[a] = idx ++;
}

int spfa() {
	memset(dist, 0x3f, sizeof dist);
	dist[1] = 0;
	q.push(1);
	st[1] = true;
	while (q.size()) {
		int u = q.front();
		q.pop();
		st[u] = false;
		for (int i = h[u]; i != -1; i = ne[i]) {
			int j = e[i];
			if (dist[j] > dist[u] + w[i]) {
			   	dist[j] = dist[u] + w[i];
			   	if(!st[j]) {
				    st[j] = true;
				    q.push(j); 
				}
				
			}
		}
	}
	return dist[n];
}



int main() {
	memset(h, -1, sizeof h);
	n = read();
	m = read();
	while (m --) {
		int a, b, c;
		a = read();
		b = read();
		c = read();
		add(a, b, c);
	}

	int res = spfa();
	if (res == 0x3f3f3f3f) puts("impossible");
	else cout << res << endl;

	return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值