图论——最短路

在这里插入图片描述
图片来自Acwing平台

本文主要内容:

  1. 朴素Dijkstra算法
  2. 堆优化Dijkstra算法
  3. Bellman-Ford算法
  4. SPFA算法
  5. Floyd算法

1 朴素Dijkstra算法

  • 主要功能:
  1. 求没有负权边的图的单源最短路
  • 时间复杂度:
    o(n2)
  • 基本思路:
  1. 假设存在一个集合s,集合中的所有节点的最短路距离已经被求解,并且存入到了dist[]中
  2. 每次挑选集合外dist值最小的节点t加入集合s,用该点更新其他所以节点
  3. 循环n次,直到所有节点加入集合s
  4. 节点t能加入集合s,因为它被集合s中的所有点更新过了,而集合外其他所有点的dist都大于等于dist[t],不可能将dist[t]更新成更小(除非集合外的节点到节点t的距离小于0

模板题:AcWing 849. Dijkstra求最短路 I

#include<iostream>
#include<cstring>

using namespace std;

const int N = 505;

int g[N][N], dist[N];
int n, m;
bool st[N];

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    for(int i = 0; i < n; i++)
    {
        int t = -1;
        for(int j = 1; j <= n; j++)
            if(!st[j] && (t == -1 || dist[j] < dist[t]))
                t = j;
        st[t] = true;
        if(t == n)break;
        for(int j = 1; j <= n; j++)
            dist[j] = min(dist[j], dist[t] + g[t][j]);//自环不会影响结果
    }
    if(dist[n] != 0x3f3f3f3f)return dist[n];
    else return -1;
}

int main()
{
    cin >> n >> m;
    memset(g, 0x3f, sizeof g);
    while(m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        g[a][b] = min(c, g[a][b]);//重边取权值较小的那条边
    }
    cout << dijkstra();
    return 0;
}

2 堆优化Dijkstra算法

  • 时间复杂度:
    o(mlogn)(n为一个大常数,m为边数)
  • 优化思路:
  1. 用一个邻接表而不是邻接矩阵来存图
  2. 用一个小根堆来存储{节点dist, 节点编号},每次选取集合外dist最小的节点x的时间复杂度从n优化到logn
  3. 每次只需用x更新与x相连的节点的dist,这样又减少一层n循环
  • 注意事项:
  1. 堆中必须允许存在重复元素,堆中元素个数可能大于节点总数

模板题:AcWing 850. Dijkstra求最短路 II

#include<iostream>
#include<cstring>
#include<queue>

using namespace std;

const int N = 150005;

typedef pair<int, int> PII;

int e[N], w[N], ne[N], h[N], idx;
bool st[N];
int n, m, dist[N];

void add(int a, int b, int c)
{
    w[idx] = c, e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int dijkstra()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    priority_queue<PII, vector<PII>, greater<PII> >heap;
    heap.push({0, 1});
    while(!heap.empty())
    {
        PII t = heap.top();
        heap.pop();
        int distance = t.first, u = t.second;
        if(u == n)break;
        if(st[u])continue;
        else st[u] = true;
        for(int i = h[u]; ~i; i = ne[i])
        {
            int j = e[i];
            if(distance + w[i] < dist[j])
            {
                dist[j] = distance + w[i];
                heap.push({dist[j], j});
            }
        }
    }
    if(dist[n] != 0x3f3f3f3f)return dist[n];
    return -1;
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while(m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    cout << dijkstra();
    return 0;
}

3 Bellman-Ford算法

  • 主要功能:
  1. 求可能存在负权边的单源最短路
  • 时间复杂度:
    o(nm)(n为节点数,m为边数)
  • 基本思路:
  1. 用一个结构体来存储所有边(包括两个端点和边权)
  2. 扫描一遍所有边,用前面端点的dist加上边权来更新后端点
  3. 扫描k遍,经过不超过k条边的所有节点的最短路已经求得
  4. 第k次扫描时,经过 k-1条边的所有节点和相应边权来更新经过k条边的所有节点的最短路
  5. 对于任意经过k条边的节点,其经过不超过k条边的最短路只会用小于k条边节点的最短路来更新
  • 注意事项:
  1. 在扫描所有边进行更新操作时因为负权边的存在,导致一些不与源点连接的点的dist小于初始化的正无穷
  2. 注意备份元素数组,避免串联问题(最短路不满足边数限制)

模板题:AcWing 853. 有边数限制的最短路

#include<iostream>
#include<cstring>

using namespace std;

const int N = 505, M = 10005, INF = 0x3f3f3f3f;

int dist[N], backup[N], n, m, k;

struct Edge
{
    int l, r, w;
}edges[M];

int bellman()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    for(int i = 1; i <= k; i++)
    {
        memcpy(backup, dist, sizeof dist);
        for(int j = 1; j <= m; j++)
        {
            Edge t = edges[j];
            int l = t.l, r = t.r, w = t.w;
            dist[r] = min(dist[r], backup[l] + w);
        }
    }
    return dist[n];
}

int main()
{
    cin >> n >> m >> k;
    for(int i = 1; i <= m; i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        edges[i] = {a, b, c};
    }
    int t = bellman();
    if(t > INF / 2)cout << "impossible";
    else cout << dist[n];
}

4 SPFA算法

  • 主要功能:
  1. 求可能存在负权边的单源最短路
  2. 判断图中是否存在负权回路
  • 时间复杂度:
    最好o(m),最坏o(nm)
  • 基本思路:
  1. 利用一个队列,用邻接表存储所有边
  2. 每次不必要更新所有边,只需要用所有相邻节点来更新当前节点,所以用邻接表(邻接表存储所有当前节点相邻节点)存储图
  3. 舍弃最外层循环,放弃边权的限制功能,采用一个队列,只要当前节点dist被更新,就将当前节点放入队列去更新其他节点(经过边数+1的节点),否则就不放入队列

模板题:Acwing851. spfa求最短路

#include<iostream>
#include<cstring>
#include<queue>

using namespace std;

const int N = 100005;

int w[N], e[N], ne[N], h[N], idx;
int n, m, dist[N];
bool st[N];

void add(int a, int b, int c)
{
    w[idx] = c, e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int spfa()
{
    memset(dist, 0x3f, sizeof dist);
    dist[1] = 0;
    queue<int>q;
    q.push(1);
    while(!q.empty())
    {
        int u = q.front();
        q.pop();
        st[u] = false;
        for(int i = h[u]; ~i; i = ne[i])
        {
            int j = e[i];
            if(j != u && dist[j] > dist[u] + w[i])
            {
                dist[j] = dist[u] + w[i];
                if(!st[j])
                {
                    q.push(j);
                    st[j] = true;
                }
            }
        }
    }
    return dist[n];
}
int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while(m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    int t = spfa();
    if(t == 0x3f3f3f3f)cout << "impossible";
    else cout << dist[n];
}

模板题2:AcWing 852. spfa判断负环

  • 思路:用一个数组cnt[]记录当前节点路径经过的边数,只要有一个cnt[]元素大于等于n,就说明图中存在负权回路
#include<iostream>
#include<cstring>
#include<queue>

using namespace std;

const int N = 2005, M = 10005;

int n, m, dist[N], cnt[N];
int w[M], e[M], ne[M], h[N], idx;
bool vis[N];

void add(int a, int b, int c)
{
    w[idx] = c, e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

bool spfa()
{
    queue<int>q;//无需初始化dist[]
    for(int i = 1; i <= n; i++)//把所有节点都放入队列,避免漏掉某些情况
        q.push(i);
    while(q.size())
    {
        int u = q.front();
        q.pop();
        vis[u] = false;
        if(cnt[u] > n - 1)return true;
        for(int i = h[u]; ~i; i = ne[i])
        {
            int j = e[i];
            if(dist[j] > dist[u] + w[i])
            {
                dist[j] = dist[u] + w[i];
                cnt[j] = cnt[u] + 1;
                if(!vis[j])
                {
                    vis[j] = true;
                    q.push(j);
                }
            }
        }
    }
    return false;
}
int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    while(m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        add(a, b, c);
    }
    if(spfa())cout << "Yes";
    else cout << "No";
    return 0;
}

5 Floyd算法

  • 主要功能:
  1. 求多源最短路
  • 时间复杂度:
    o(n3)
  • 基本思路:
  1. 状态表示,f[i][j]表示节点i到节点j的所有路径、属性为最小路径距离
  2. f[i][j] = min(f[i][j], f[i][k] + f[k][j])(此时任意两点的所有路径的中间节点属于1~k-1的两点距离已经最短,在k-1层循环的时候被更新,f[i][j]实际上是被中间节点属于1~k-1的f[i][k]、f[k][j]最小路径值更新)
  3. 初始化:当k等于1时,k-1等于0,而中间节点为1~0的路径不存在,所以无需初始化
  • 注意事项:
  1. 外层循环为k
  2. 每个节点到其本身的距离初始化为0,到其他节点的距离初始化为正无穷

模板题:AcWing 854. Floyd求最短路

#include<iostream>
#include<cstring>

using namespace std;

const int N = 205;

int n, m, q, d[N][N];

void floyd()
{
    for(int k = 1; k <= n; k++)
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}

int main()
{
    cin >> n >> m >> q;
    memset(d, 0x3f, sizeof d);
    for(int i = 1; i <= n; i++)
        d[i][i] = 0;
    while(m--)
    {
        int a, b, c;
        cin >> a >> b >> c;
        d[a][b] = min(d[a][b], c);
    }
    floyd();
    while(q--)
    {
        int a, b;
        cin >> a >> b;
        if(d[a][b] > 0x3f3f3f3f / 2)cout << "impossible" << endl;
        else cout << d[a][b] << endl;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]提供了使用Python的networkx库绘制网络图和计算最短加权路径的示例代码。该代码使用了一个包含顶点和边的列表,并使用add_nodes_from和add_weighted_edges_from方法将它们添加到图中。然后,使用nx.shortest_path_length方法计算了从顶点v1到顶点v11的最短加权路径长度为13。\[1\] 引用\[2\]提供了一个计算最短路径的Python程序示例。该程序使用了numpy和networkx库。首先,定义了一个包含顶点和边的列表,并使用add_nodes_from和add_weighted_edges_from方法将它们添加到图中。然后,使用nx.shortest_path_length方法计算了最短路径长度,并将结果存储在一个字典中。接下来,使用numpy创建了一个6x6的零矩阵,并使用两个嵌套的for循环将最短路径长度填充到矩阵中。最后,使用矩阵乘法计算了运力,并找到了最小运力和对应的位置。\[2\] 引用\[3\]提供了关于Dijkstra算法的一些背景信息。Dijkstra算法是一种寻找最短路径的算法,适用于所有权重大于等于0的情况。它可以用于解决从一个起始点到任意一个点最短路径问题。\[3\] 综上所述,如果你想在Python中计算图论中的最短路径,可以使用networkx库和Dijkstra算法。你可以根据引用\[1\]和引用\[2\]中的示例代码进行操作。 #### 引用[.reference_title] - *1* *3* [运筹学——图论与最短距离(Python实现)](https://blog.csdn.net/weixin_46039719/article/details/122521276)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [数学建模:图论模型 — 最短路模型示例 (Python 求解)](https://blog.csdn.net/qq_55851911/article/details/124776487)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值