SPFA的卓越之处就在于处理多点稀疏图,因为点太多的话,我们直接用矩阵来存图的话是存不下的。
所以当我们用邻接矩阵来存图的话,我们就可以用SPFA来解决这类问题,spfa就是优化版的bellman-ford算法。
当我们无法对于单源最短路进行更新的话,说明所有的从起点出发的路已经都是最优了,这时候,我们的广搜也就结束了,
我们的spfa也就结束了。
挂一个写的很好的博客吧,博主懒,就不写了。
https://blog.csdn.net/muxidreamtohit/article/details/7894298
带图解哦!
#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100005;
const int INF = 0x7f7f7f7f;
vector<int> v1[maxn];
vector<int> v2[maxn];
int n, m, s, t;
int d[maxn],isque[maxn];
void spfa()
{
d[s] = 0;
queue<int> q;
q.push(s);
isque[s] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
isque[u] = 0;
for (int i = 0; i < v1[u].size();i++) {
int v = v1[u][i];
int len = v2[u][i];
if (d[v]>d[u]+len) {
d[v] = d[u] + len;
if (!isque[v]) {
q.push(v);
isque[v] = 1;
}
}
}
}
}
int main()
{
scanf("%d%d%d%d", &n, &m, &s, &t);
int u, v, c;
for (int i = 0; i < m;i++) {
scanf("%d%d%d", &u, &v, &c);
v1[u].push_back(v);
v1[v].push_back(u);
v2[u].push_back(c);
v2[v].push_back(c);
}
memset(d, INF, sizeof(d));
memset(isque, 0, sizeof(isque));
spfa();
printf("%d\n", d[t]);
return 0;
}