SPFA算法
万圣节的晚上,小Hi和小Ho在吃过晚饭之后,来到了一个巨大的鬼屋!
鬼屋中一共有N个地点,分别编号为1…N,这N个地点之间互相有一些道路连通,两个地点之间可能有多条道路连通,但是并不存在一条两端都是同一个地点的道路。
不过这个鬼屋虽然很大,但是其中的道路并不算多,所以小Hi还是希望能够知道从入口到出口的最短距离是多少?
Input
每个测试点(输入文件)有且仅有一组测试数据。
在一组测试数据中:
第1行为4个整数N、M、S、T,分别表示鬼屋中地点的个数和道路的条数,入口(也是一个地点)的编号,出口(同样也是一个地点)的编号。
接下来的M行,每行描述一条道路:其中的第i行为三个整数u_i, v_i, length_i,表明在编号为u_i的地点和编号为v_i的地点之间有一条长度为length_i的道路。
对于100%的数据,满足N<=105,M<=106, 1 <= length_i <= 10^3, 1 <= S, T <= N, 且S不等于T。
对于100%的数据,满足小Hi和小Ho总是有办法从入口通过地图上标注出来的道路到达出口。
Output
对于每组测试数据,输出一个整数Ans,表示那么小Hi和小Ho为了走出鬼屋至少要走的路程。
Sample Input
5 10 3 5
1 2 997
2 3 505
3 4 118
4 5 54
3 5 480
3 4 796
5 2 794
2 5 146
5 4 604
2 5 63
Sample Output
172
SPFA算法:
可用于求最短路径,但其复杂度随数据变化而不定。
也可用于判断负环。
算法的具体实现过程与BFS相似,需要一个队列queue,在弹出首元素将其子元素加入队列是要判断距离是否需要更新。如果距离需要更新,这才把这个子元素加入队列中。
代码:
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#define INF 0x3f3f3f3f
#define mod 998244353
#define PI acos(-1)
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
vector<pii > g[100005];
int dis[100005];
int n, m, s, t;
int vis[100005];
queue<int> q;
void spfa(int s)
{
for (int i = 1; i <= 100000; i++)
dis[i] = 99999999;
q.push(s);
dis[s] = 0;
vis[s] = 1;
while (!q.empty()) {
int now = q.front(); q.pop();
vis[now] = 0;
for (auto to : g[now])
{
int v = to.first; int w = to.second;
if (dis[now] + w < dis[v]) { // 更新
dis[v] = dis[now] + w;
if (!vis[v]) {
vis[v] = 1;
q.push(v);
}
}
}
}
}
int main()
{
cin >> n >> m >> s >> t;
while (m--)
{
int u, v, d;
cin >> u >> v >> d;
g[u].push_back({ v, d });
g[v].push_back({ u, d });
}
spfa(s);
printf("%d\n", dis[t]);
}