今天我们来聊一聊单源最短路径。(开始爆更)昨天我们学习了图论,忘记的小伙伴们可以看一下
这里写目录标题
单源是什么意思?
固定一个起点,求它到所有点的最短路径的问题。
Bellman-FORD算法
我们假设d[i]表示的起点(记为s)到第i个点的最短距离,我们直接从已知点出发,只要找到与已知点相邻的边,那么就更新距离,遍历所有的点每一次d一定都是最短的距离
实现
首先保存边,距离,点数和边数
struct edge
{
int from,to,cost;
}
edge es[M];
int d[M];
int V,E;
初始化
d[i]=INF;
d[s]=0;
接下来就是更新d
//不知道要更新多少次
while(true)
{
bool flag = false;//如果在这一次循环中没有更新,那么说明所有已知点出发的边已经找完了,可以退出了
for (int i = 0; i < E; i++)
{
edge e=es[i];
if(d[e.from] != INF && d[e.to] > d[e.from] + e.cost)
{
d[e.to] = d[e.from]+e.cost;
flag = true;
}
}
if(!flag) break;
}
完整实现
#include <iostream>
#include <vector>
using namespace std;
const int M=1e5;
const int INF=0xfffffff;
struct edge
{
int from,to,cost;
};
edge es[M];
int d[M];
int V,E;
//顶点S出发到所有点的最短路劲
void shortest_path(int s)
{
for (int i = 0; i < V; i++)
{
d[i]=INF;
}
d[s] = 0;
while(true)
{
bool update = false;
for (int i = 0; i < E; i++)
{
edge e=es[i];
if(d[e.from] != INF && d[e.to] > d[e.from] + e.cost)
{
d[e.to] = d[e.from]+e.cost;
update = true;
}
}
if(!update) break;
}
}
如果发现没有负数的边,每个边最多使用一次,也就是说while最多循环V-1次,因此这个算法的时间复杂度是O(V*E)
好了,今天的最短路径1就到这里啦!
如果有任何问题欢迎和我交流:shirandexiaowo@foxmail.com