SPFA算法_带负权边的单源最短路径

PSFA算法是Bellman_ford算法的一个优化,他的核心思想是:
如果当前结点到源点的距离变短了,那么和他有边的结点到源点的距离有可能会变短。
伪码描述:

q.push(1);
st[1] = true;
while(!q.empty()){
    
    
	v = q.front(),q.pop();
	st[v] = false;
	for x in graph[v]{
    
    
		if(dis[x]>dis[v]+w){
    
    
			dis[x] = dis[v]+w;
			if(x不在队列中){
    
    
				q.push(x);
				st[x]=true;
			}
		}
	}
}

题目描述:
在这里插入图片描述

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

using namespace std;

const int N = 1e5+5;

typedef struct node {
    
    
	int b, w;
}node;

queue<int > q;
vector<node > graph[N];
int n, m, k;
int st[N], dis[N];

int spfa() {
    
    
	memset(dis, 0x3f, sizeof dis);
	//队列存放到源点距离发送了变化了边
	q.push(1);
	st[1] = true;//结点在队列中
	dis[1] = 0;
	while (q.size()) {
    
    
		int v = q.front();
		q.pop();
		st[v] = false;//结点不在队列中
		for (auto x : graph[v]) {
    
    
			if (dis[x.b] > dis[v] + x.w) {
    
    
				//更新到源点的距离
				dis[x.b] = dis[v] + x.w;
				if (!st[x.b]) {
    
    
					st[x.b] = true;
					q.push(x.b);
				}
			}
		}
	}
	if (dis[n] == 0x3f3f3f3f) {
    
    
		//源点无法到n结点
		return -1;
	}
	else {
    
    
		return dis[n];
	}
}

int main() {
    
    
	cin >> n >> m;
	for (int i = 0; i < m; i++) {
    
    
		int a, b, w;
		cin >> a >> b >> w;
		//构建邻接表
		graph[a].push_back({
    
     b,w });
	}
	int k = spfa();
	if (k == -1) {
    
    
		cout << "impossible" << endl;
	}
	else {
    
    
		cout << k << endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45931661/article/details/119571980