栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

Leetcode 743/1514 单源最短路Dijkstra算法介绍

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Leetcode 743/1514 单源最短路Dijkstra算法介绍

算法描述:

每次从未标记节点中找到从起点到该点路径最小的点,标记为已经完成的点,然后跟新所有与该点临接的点的路径值。可以证明,执行n次这样的操作,就可以找到从起点到图中各个点的最短路。

由此解决Leetcode 743. 网络延迟时间, 找出图中所有路径单源最短路的最大值。

class Solution {
public:
    int networkDelayTime(vector> ×, int n, int k) {
        const int inf = INT_MAX / 2;
        vector> g(n, vector(n, inf));
        for (auto &t : times) {
            int x = t[0] - 1, y = t[1] - 1;
            g[x][y] = t[2];
        }

        vector dist(n, inf);
        dist[k - 1] = 0;
        vector used(n);
        for (int i = 0; i < n; ++i) {
            int x = -1;
            for (int y = 0; y < n; ++y) {
                if (!used[y] && (x == -1 || dist[y] < dist[x])) {
                    x = y;
                }
            }
            used[x] = true;
            for (int y = 0; y < n; ++y) {
                dist[y] = min(dist[y], dist[x] + g[x][y]);
            }
        }

        int ans = *max_element(dist.begin(), dist.end());
        return ans == inf ? -1 : ans;
    }
};

该算法可以进一步优化,由于我们需要每次找出未标记点中路径最小的点,所以我们想到用小根堆,将该点取出时,该点已经被标记过了,就出队,也不需要用bool数组来标记。那么一开始是否需要将所有边入队,答案是不需要,只需要在每次松弛操作时入队即可。

class Solution {
public:
    int networkDelayTime(vector> ×, int n, int k) {
        const int inf = INT_MAX / 2;
        vector>> g(n);
        for (auto &t : times) {
            int x = t[0] - 1, y = t[1] - 1;
            g[x].emplace_back(y, t[2]);
        }

        vector dist(n, inf);
        dist[k - 1] = 0;
        priority_queue, vector>, greater<>> q;
        q.emplace(0, k - 1);
        while (!q.empty()) {
            auto p = q.top();
            q.pop();
            int time = p.first, x = p.second;
            if (dist[x] < time) {
                continue;
            }
            for (auto &e : g[x]) {
                int y = e.first, d = dist[x] + e.second;
                if (d < dist[y]) {
                    dist[y] = d;
                    q.emplace(d, y);
                }
            }
        }

        int ans = *max_element(dist.begin(), dist.end());
        return ans == inf ? -1 : ans;
    }
};

Leetcode 1514 概率最大的路径也可以转化为该算法解决。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/297235.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号