void spfa(int s)
{
for (int i = 1; i <= nov; ++i)
{
// 初始化。远点到任一点的距离都是正无穷
dis[i] = INF;
// 所有点(除原点)都未入队
vis[i] = 0;
}
// 远点到自己的距离为 0,原点在队列里
dis[s] = 0;
// 这句可以不写
vis[s] = 1;
queue<int> q;
q.push(s);
while (!q.empty())
{
int t = q.front();
q.pop();
vis[t] = 0;
for (int i = head[t]; i; i = e[i].nex)
{
int to = e[i].to;
// 从 s 到 t 再到 t 的 i 号子节点的路径长
// 比从 s 直接到 t 的 i 号子节点短
// 进行松弛操作
if (dis[to] > dis[t] + e[i].val)
{
dis[to] = dis[t] + e[i].val;
// 如果没入队,那就入队
if (!vis[to])
{
q.push(to);
vis[to] = 1;
}
}
}
}
}
OI退役笔记-015:图论(二)最短路(Floyed、Dijkstra、Bellman-Ford、SPFA)
最新推荐文章于 2021-05-27 23:19:10 发布