思路:与Bellman_ford算法核心思路几乎一致,即重复松弛,但是相较于Bellman_ford算法有改进的是,spfa不再无脑更新所有边,而是松弛那些被松弛过的和松弛点有关的边,因为只有被松弛过的点才有可能去松弛其他的点,所以会开一个队列保存可能会被松驰的点,通过这些点来松弛其他可松弛的点。
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
const int N = 1e5 + 10;
int n,m;
int h[N],e[N],ne[N],w[N],idx,dist[N];
bool st[N];//用于判断该点是否在队列内
void add(int a,int b,int c)//理同 846
{
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
int spfa()
{
queue<int> q;
memset(dist,0x3f,sizeof dist);
dist[1] = 0;
q.push(1);
st[1] = true;
while(q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t];i != -1;i = ne[i])
{
int j = e[i];
if(dist[j] > dist[t] + w[i])//如果最短路径能够更新的话
{
dist[j] = dist[t] + w[i];
if(!st[j])//且j对应的点不在队列内
{
q.push(j);
st[j] = true;
}
}
}
}
return dist[n];
}
int main()
{
scanf("%d%d",&n,&m);
memset(h,-1,sizeof h);
while(m--)
{
int a, b, w;
scanf("%d%d%d",&a,&b,&w);
add(a,b,w);
}
int res = spfa();
if(res == 0x3f3f3f3f) puts("impossible");
else printf("%d",res);
return 0;
}
SPFA算法实现与理解
文章介绍了SPFA(ShortestPathFasterAlgorithm)算法,它是求解图中单源最短路径的一种方法。SPFA在思想上类似于Bellman-Ford算法,通过不断松弛路径来更新最短距离,但优化了更新策略,只对可能影响最短路径的节点进行处理,使用队列来管理这些节点。文章通过代码展示了SPFA算法的实现过程,并在最后给出了一个简单的主函数示例。
1070

被折叠的 条评论
为什么被折叠?



