Bellman-Ford算法

算法

以边为研究对象的最短路算法。

应用场景

  1. 有负边权的最短路问题。

  2. 负环的判定。

算法原理

  1. \(n\) 个点的最短路径最多经过 \(n - 1\) 条边。

  2. 每条边要么经过,要么不经过,对于一条边的两个端点 \(x\) 和 \(y\)。

    所以我们把每一条边都枚举一遍看是否可以进行松弛。

  3. 将步骤 \(2\) 重复 \(n - 1\) 轮后,\(dis[i]\) 即为起点到达点 \(i\) 的最短路。

代码:

for (int i = 1; i <= n - 1; i++)
for (int j = 1; j <= m; j++)
if (dis[e[j].x] + e[j].w < dis[e[j].y])
dis[e[j].y] = dis[e[j].x] + e[j].w;

时间复杂度

显然是\(O(nm)\)。

Bellman-Ford算法的队列优化(SPFA)

  1. 一个点只会松弛它的邻接点,因此,只有 \(x\) 的邻接点的 \(y\) 被松驰过,点 \(x\) 才有松弛的必要。

  2. 用队列维护被松弛过的点集。

  3. 对于随机数据优化明显,但是最坏情况时间复杂度仍然为 \(O(nm)\)。

模板:Luogu P3371

1.SPFA代码

#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <queue> using namespace std; const int N = 10010, M = 500010, INF = 0x3f3f3f3f; struct Edge
{
int to;
int next;
int w;
}e[M]; int head[N], idx; void add(int a, int b, int c)
{
idx++, e[idx].to = b, e[idx].next = head[a], e[idx].w = c, head[a] = idx;
} int n, m, s;
int dis[N]; void spfa(int u)
{
queue<int> q;
q.push(u);
memset(dis, 0x3f, sizeof(dis));
dis[u] = 0; while (q.size())
{
int t = q.front();
q.pop(); for (int i = head[t]; i; i = e[i].next)
{
int to = e[i].to;
if (dis[to] > dis[t] + e[i].w)
{
dis[to] = dis[t] + e[i].w;
q.push(to);
}
}
}
} int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr); cin >> n >> m >> s; for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
} spfa(s); for (int i = 1; i <= n; i++)
{
if (dis[i] == INF) cout << INT_MAX << ' ';
else cout << dis[i] << ' ';
}
return 0;
}

2. 优化1:加一个st数组,防止元素重复进队列。

快了215ms

重点关注第27,35,41,49,50,51,52,53行。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <queue> using namespace std; const int N = 10010, M = 500010, INF = 0x3f3f3f3f; struct Edge
{
int to;
int next;
int w;
}e[M]; int head[N], idx; void add(int a, int b, int c)
{
idx++, e[idx].to = b, e[idx].next = head[a], e[idx].w = c, head[a] = idx;
} int n, m, s;
int dis[N];
bool st[N]; void spfa(int u)
{
queue<int> q;
q.push(u);
memset(dis, 0x3f, sizeof(dis));
dis[u] = 0;
st[u] = true; while (q.size())
{
int t = q.front();
q.pop();
st[t] = false; for (int i = head[t]; i; i = e[i].next)
{
int to = e[i].to;
if (dis[to] > dis[t] + e[i].w)
{
dis[to] = dis[t] + e[i].w;
if (!st[to])
{
st[to] = true;
q.push(to);
}
}
}
}
} int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr); cin >> n >> m >> s; for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
} spfa(s); for (int i = 1; i <= n; i++)
{
if (dis[i] == INF) cout << INT_MAX << ' ';
else cout << dis[i] << ' ';
}
return 0;
}

3. 优化2:SLF 优化

每次压入队列时,是看放后面还是前面,所以需要双端队列。

快了18ms

重点关注代码第31,52,53行。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <queue> using namespace std; const int N = 10010, M = 500010, INF = 0x3f3f3f3f; struct Edge
{
int to;
int next;
int w;
}e[M]; int head[N], idx; void add(int a, int b, int c)
{
idx++, e[idx].to = b, e[idx].next = head[a], e[idx].w = c, head[a] = idx;
} int n, m, s;
int dis[N];
bool st[N]; void spfa(int u)
{
deque<int> q;
q.emplace_back(u);
memset(dis, 0x3f, sizeof(dis));
dis[u] = 0;
st[u] = true; while (q.size())
{
int t = q.front();
q.pop_front();
st[t] = false; for (int i = head[t]; i; i = e[i].next)
{
int to = e[i].to;
if (dis[to] > dis[t] + e[i].w)
{
dis[to] = dis[t] + e[i].w;
if (!st[to])
{
st[to] = true;
if (q.size() && dis[q.front()] >= dis[to]) q.emplace_front(to);
else q.emplace_back(to);
}
}
}
}
} int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr); cin >> n >> m >> s; for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
} spfa(s); for (int i = 1; i <= n; i++)
{
if (dis[i] == INF) cout << INT_MAX << ' ';
else cout << dis[i] << ' ';
}
return 0;
}

4. 优化3:此优化仅针对不开O2优化时。

使用循环队列进行优化(我改编的)。

(开了O2优化效果不明显,亲自测试在跑网络流时快了800ms,TLE->AC)

#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <queue> using namespace std; const int N = 10010, M = 500010, INF = 0x3f3f3f3f; struct Edge
{
int to;
int next;
int w;
}e[M]; int head[N], idx; void add(int a, int b, int c)
{
idx++, e[idx].to = b, e[idx].next = head[a], e[idx].w = c, head[a] = idx;
} int n, m, s;
int dis[N];
bool st[N]; int q[N];
int hh, tt;
int sz; void push_back(int x)
{
sz++;
q[tt++] = x;
if (tt == N) tt = 0;
} void push_front(int x)
{
sz++;
hh--;
if (hh == -1) hh = N - 1;
q[hh] = x;
} void pop_back()
{
sz--;
tt--;
if (tt == -1) tt = N - 1;
} void pop_front()
{
sz--;
hh++;
if (hh == N) hh = 0;
} void spfa(int u)
{
push_back(u);
memset(dis, 0x3f, sizeof(dis));
dis[u] = 0;
st[u] = true; while (sz)
{
int t = q[hh];
pop_front();
st[t] = false; for (int i = head[t]; i; i = e[i].next)
{
int to = e[i].to;
if (dis[to] > dis[t] + e[i].w)
{
dis[to] = dis[t] + e[i].w;
if (!st[to])
{
st[to] = true;
if (sz && dis[q[hh]] >= dis[to]) push_front(to);
else push_back(to);
}
}
}
}
} int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr); cin >> n >> m >> s; for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
} spfa(s); for (int i = 1; i <= n; i++)
{
if (dis[i] == INF) cout << INT_MAX << ' ';
else cout << dis[i] << ' ';
}
return 0;
}

5. 优化4:LLL优化

如果当前队首元素 \(t\),队列长度为 \(size\),队列里各元素和为 \(sum\) ,有 \(dis[t] \times size \leq sum\),才取队首。

否则把队首元素压入队尾并弹出队首。

效果好像不怎么明显

重点关注代码的第68,72,73,74,75,76,91行。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <climits>
#include <queue> using namespace std; const int N = 10010, M = 500010, INF = 0x3f3f3f3f; struct Edge
{
int to;
int next;
int w;
}e[M]; int head[N], idx; void add(int a, int b, int c)
{
idx++, e[idx].to = b, e[idx].next = head[a], e[idx].w = c, head[a] = idx;
} int n, m, s;
int dis[N];
bool st[N]; int q[N];
int hh, tt;
int sz; void push_back(int x)
{
sz++;
q[tt++] = x;
if (tt == N) tt = 0;
} void push_front(int x)
{
sz++;
hh--;
if (hh == -1) hh = N - 1;
q[hh] = x;
} void pop_back()
{
sz--;
tt--;
if (tt == -1) tt = N - 1;
} void pop_front()
{
sz--;
hh++;
if (hh == N) hh = 0;
} void spfa(int u)
{
push_back(u);
memset(dis, 0x3f, sizeof(dis));
dis[u] = 0;
st[u] = true;
int sum = dis[u]; while (sz)
{
while (dis[q[hh]] * sz > sum)
{
push_back(q[hh]);
pop_front();
}
int t = q[hh];
pop_front();
st[t] = false;
sum -= dis[t]; for (int i = head[t]; i; i = e[i].next)
{
int to = e[i].to;
if (dis[to] > dis[t] + e[i].w)
{
dis[to] = dis[t] + e[i].w;
if (!st[to])
{
st[to] = true;
sum += dis[to];
if (sz && dis[q[hh]] >= dis[to]) push_front(to);
else push_back(to);
}
}
}
}
} int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr); cin >> n >> m >> s; for (int i = 1; i <= m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
} spfa(s); for (int i = 1; i <= n; i++)
{
if (dis[i] == INF) cout << INT_MAX << ' ';
else cout << dis[i] << ' ';
}
return 0;
}

本文终

Bellman-Ford算法及SPFA算法的思路及进一步优化的更多相关文章

  1. 数据结构与算法--最短路径之Bellman算法、SPFA算法

    数据结构与算法--最短路径之Bellman算法.SPFA算法 除了Floyd算法,另外一个使用广泛且可以处理负权边的是Bellman-Ford算法. Bellman-Ford算法 假设某个图有V个顶点 ...

  2. 最短路径——Bellman-Ford算法以及SPFA算法

    说完dijkstra算法,有提到过朴素dij算法无法处理负权边的情况,这里就需要用到Bellman-Ford算法,抛弃贪心的想法,牺牲时间的基础上,换取负权有向图的处理正确. 单源最短路径 Bellm ...

  3. Bellman-ford算法、SPFA算法求解最短路模板

    Bellman-ford 算法适用于含有负权边的最短路求解,复杂度是O( VE ),其原理是依次对每条边进行松弛操作,重复这个操作E-1次后则一定得到最短路,如果还能继续松弛,则有负环.这是因为最长的 ...

  4. Bellman-Ford算法与SPFA算法详解

    PS:如果您只需要Bellman-Ford/SPFA/判负环模板,请到相应的模板部分 上一篇中简单讲解了用于多源最短路的Floyd算法.本篇要介绍的则是用与单源最短路的Bellman-Ford算法和它 ...

  5. 最短路径算法 4.SPFA算法(1)

    今天所说的就是常用的解决最短路径问题最后一个算法,这个算法同样是求连通图中单源点到其他结点的最短路径,功能和Bellman-Ford算法大致相同,可以求有负权的边的图,但不能出现负回路.但是SPFA算 ...

  6. 图论之最短路算法之SPFA算法

    SPFA(Shortest Path Faster Algorithm)算法,是一种求最短路的算法. SPFA的思路及写法和BFS有相同的地方,我就举一道例题(洛谷--P3371 [模板]单源最短路径 ...

  7. 最短路径算法之四——SPFA算法

    SPAF算法 求单源最短路的SPFA算法的全称是:Shortest Path Faster Algorithm,该算法是西南交通大学段凡丁于1994年发表的. 它可以在O(kE)的时间复杂度内求出源点 ...

  8. 最短路径问题---Floyed(弗洛伊德算法),dijkstra算法,SPFA算法

    在NOIP比赛中,如果出图论题最短路径应该是个常考点. 求解最短路径常用的算法有:Floyed算法(O(n^3)的暴力算法,在比赛中大概能过三十分) dijkstra算法 (堆优化之后是O(MlogE ...

  9. hdoj 1874 畅通工程续【dijkstra算法or spfa算法】

    畅通工程续 Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total Submi ...

  10. Bellman-ford算法与SPFA算法思想详解及判负权环(负权回路)

    我们先看一下负权环为什么这么特殊:在一个图中,只要一个多边结构不是负权环,那么重复经过此结构时就会导致代价不断增大.在多边结构中唯有负权环会导致重复经过时代价不断减小,故在一些最短路径算法中可能会凭借 ...

随机推荐

  1. 【SSM项目】尚筹网(三)基于Servlet3.0项目搭建:异常映射和拦截器机制

    1 异常映射 1.1 目标 使用异常映射对项目的异常和错误提示进行统一管理. 1.2 思路 对于普通的页面请求,异常映射机制捕获到handler方法抛出的异常后会响应为一个错误页面,对于处理ajax请 ...

  2. LNMP搭建静态网页服务器

    chattr -i default/.user.ini LNMP搭建使用 1.安装screen,命令或者操作可以一直运行下去 yum install screen 2.获取及安装 LNMP wget ...

  3. React课堂笔记2

    一.JSX 1.1.什么是JSX JSX = JavaScript XML,这是React官方发明的一种JS语法(糖) 概念:JSX是 JavaScript XML(HTML)的缩写,表示在 JS 代 ...

  4. VUE3企业级项目基础框架搭建流程(2)

    typescript安装 这里使用的vue项目语言为:TypeScript,不了解的可以先去学习一下.TypeScript中文网 正常情况下安装typescript的命令为: // 全局安装 npm ...

  5. CentOS配置Django虚拟环境--坑点总结

    1.CentOS原装有python2.7,编译安装python3.X版本 2.sqlite-devel未安装 3.sqlite3版本过低报错 升级sqlite3版本 参考 https://blog.c ...

  6. windows下MinGW编译ffmpeg

    windows下MinGW编译ffmpeg 1.官网下载MinGW并安装       1)下载 ,下载网址: https://sourceforge.net/projects/mingw/files/ ...

  7. ECharts 环形饼图配置

    官网文档:https://echarts.apache.org/zh/option.html#series-pie.type 使用案例指导:https://echarts.apache.org/zh/ ...

  8. python 编程规范有哪些?

    Python 编程规范主要包括代码布局.命名规范.注释规范.函数编写规范等多个方面,下面给出一些常见的编程规范及其示例代码. 1. 代码布局规范 代码布局规范主要是指代码的缩进.行宽.空行.换行等方面 ...

  9. 【Docker】镜像管理

    一.搜索镜像 1.在官方网站搜索镜像 Docker 官方镜像仓库:https://hub.docker.com/ 2.docker search 搜索镜像 Usage: docker search [ ...

  10. ai问答:使用 Vue3 组合式API 和 TS 封装 echarts 折线图

    使用这个组件时,只需要传入合适的chartData数组,就可以渲染一个折线图,并且响应数据变化. <template> <div ref="chart" styl ...