SPFA算法,即Shortest Path Faster Algorithm。
首先假设用 b f s bfs bfs解决最短路径
构造一个队列,最开始队列里只有(S, 0)——表示当前处于点S,从点S到达该点的距离为0,然后每次从队首取出一个节点(i, L)——表示当前处于点i,从点S到达该点的距离为L,接下来遍历所有从这个节点出发的边(i, j, l)——表示i和j之间有一条长度为l的边,将(j, L+l)加入到队尾,最后看所有遍历的(T, X)节点中X的最小值就是答案。
加入优化:
SPFA算法呢,其实某种意义上就是宽度优先搜索的优化——如果你在尝试将(p, q)加入到队尾的时候,发现队列中已经存在一个(p, q’)了,那么你就可以比较q和q’:如果q>=q’,那么(p, q)这个节点实际上是没有继续搜索下去的必要的——算是一种最优化剪枝吧。而如果q<q’,那么(p, q’)也是没有必要继续搜索下去的——但是它已经存在于队列里了怎么办呢?很简单,将队列中的(p, q’)改成(p, q)就可以了!
hihocoder#1093-最短路径
#include <cstdio>
#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#define INF 0x3f3f3f3f
#define d(x) cout << (x) << endl
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod = 9999991;
const int N = 1e5 + 10;
const int M = 1e6 + 10;
struct edge{
int next, to, w;
} e[M];
int head[M];
int n, m, s, t, x, y, z;
int cnt = 0;
int dis[N], vis[N];
void add(int x, int y, int z){
e[cnt].to = y;
e[cnt].w = z;
e[cnt].next = head[x];
head[x] = cnt++;
}
void spfa(){
queue<int> q;
q.push(s);
vis[s] = 1;
while(!q.empty()){
int k = q.front();
q.pop();
vis[k] = 0;
for(int i = head[k]; i != -1; i = e[i].next){
int to = e[i].to;
int w = e[i].w;
if(dis[to] > dis[k] + w){
dis[to] = dis[k] + w;
if(!vis[to]){
q.push(to);
vis[to] = 1;
}
}
}
}
printf("%d\n", dis[t]);
}
int main()
{
memset(head, -1, sizeof(head));
memset(dis, INF, sizeof(dis));
scanf("%d%d%d%d", &n, &m, &s, &t);
while(m--){
scanf("%d%d%d", &x, &y, &z);
add(x, y, z);
add(y, x, z);
}
dis[s] = 0;
spfa();
return 0;
}
/*
*/