图论算法(四) Dijkstra算法

代码

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;

const int INF = 0x3f3f3f3f;

struct Edge {
    int vertex, weight;
};

class Graph {
private:
    int n;
    vector<Edge> * edges;
    bool * visited;
public:
    int * dist;
    Graph (int input_n) {
        n = input_n;
        edges = new vector<Edge>[n];
        dist = new int[n];
        visited = new bool[n];
        memset(visited, 0, n);
        memset(dist, 0x3f, n * sizeof(int));
    }
    ~Graph() {
        delete[] dist;
        delete[] edges;
        delete[] visited;
    }
    void insert(int x, int y, int weight) {
        edges[x].push_back(Edge{y, weight});
        edges[y].push_back(Edge{x, weight});
    }
    void dijkstra(int v) {
        dist[v]=0; //从v出发,首先将v的距离设置为0(自己到自己)
        for(int i=0;i<n;i++){ //遍历所有其他结点
            int min_dist=INF,min_vertex;  //初始化一个最短距离和当前距离最短的节点
            for(int j=0;j<n;j++){
                if(!visited[j]&&dist[j]<min_dist){ 如果当前结点的距离比min_dist小则更新之
                    min_dist=dist[j];
                    min_vertex=j;
                }  
            }
            visited[min_vertex]=1;//标记已访问
            for (Edge& j:edges[min_vertex]){//遍历min_vertex的每一条边
                if(min_dist+j.weight<dist[j.vertex]){//如果当前的最小距离,加上边的距离小于j.vertex的距离的话就更新j.vertex的距离——这意味着j.vertex的距离没那么大
                    dist[j.vertex]=min_dist+j.weight;
                }
            }
        }
        
    }
};

int main() {
    int n, m;
    cin >> n >> m;
    Graph g(n);
    for (int i = 0; i < m; i++) {
        int a, b, c;
        cin >> a >> b >> c;
        g.insert(a, b, c);
    }
    g.dijkstra(0);
    for (int i = 0; i < n; i++) {
        cout << i << ": " << g.dist[i] << endl;
    }
    return 0;
}

Dijkstra算法的思路:
参见代码注释

    原文作者:qratosone
    原文地址: https://www.jianshu.com/p/a9e6f0731a6a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞