其他分享
首页 > 其他分享> > Dijkstra

Dijkstra

作者:互联网

题目:
LeetCode 743. 网络延迟时间。给定无负边图,求信号从某一源点散播到所有点的最短时间。

分析:
单源最短路问题,这里用Dijkstra算法实现。有几个注意点:优先队列调用的>需要用友元函数,参数为const xx&;优先队列波认为大根堆。另外这里选用链式前向星存图。

代码:

const int MAXE = 6010;
const int MAXV = 110;
const int inf = 0x3f3f3f3f;

struct edge {
    int from, to, weight, next;
};

struct QNode {
    int v, dis;
    QNode(int v_, int dis_) :v(v_), dis(dis_) {}
    friend bool operator < (const QNode& lhs, const QNode& rhs) {
        return lhs.dis > rhs.dis;
    }
};

class Solution {
public:
    int networkDelayTime(vector<vector<int>>& times, int n, int k) {
        for (auto time : times) {
            int u = time[0], v = time[1], weight = time[2];
            add_edge(u, v, weight);
        }
        memset(dis, inf, sizeof(dis));
        priority_queue<QNode> queue;
        queue.push(QNode(k, 0));
        dis[k] = 0;
        while (!queue.empty()) {
            QNode q = queue.top();
            queue.pop();
            if (vis[q.v])
                continue;
            vis[q.v] = 1;
            dis[q.v] = q.dis;
            for (int i = head[q.v]; i; i = edges[i].next) {
                if (!vis[edges[i].to]) {
                    queue.push(QNode(edges[i].to, q.dis + edges[i].weight));
                }
            }
        }
        int ma = 0;
        for (int i = 1;i <= n;i++) {
            if (dis[i] == inf) {
                ma = -1;
                break;
            }
            else {
                ma = max(ma, dis[i]);
            }
        }
        return ma;
    }

    int head[MAXV], tot, vis[MAXV], dis[MAXV];
    edge edges[MAXE];

    void add_edge(int u, int v, int weight) {
        edges[++tot] = { u,v,weight,head[u] };
        head[u] = tot;
    }
};

标签:const,weight,int,queue,Dijkstra,QNode,dis
来源: https://www.cnblogs.com/Unparalleled-Calvin/p/16241230.html