Dijkstra

Posted adventurer-h

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Dijkstra相关的知识,希望对你有一定的参考价值。

#include <bits/stdc++.h>
#define N 200001
#define M 500001
#define pr pair<int,int>
#define mk make_pair

using namespace std;

const int INF = 0x7fffffff;

struct Node{
    int v,val,nxt;
}e[M];

int n,m,s,top;
int dist[N],head[N];

void add(int u,int v,int w){
    ++top;
    e[top].v = v;
    e[top].val = w;
    e[top].nxt = head[u];
    head[u] = top;
}

priority_queue<pr,vector<pr>,greater<pr> > q;
void Dijkstra(){
    for(int i = 1; i <= n; ++i) dist[i] = INF;
    dist[s] = 0;
    q.push(mk(0, s));
    while(!q.empty()){
        int u = q.top().second;
        int d = q.top().first;
        q.pop();
        if(dist[u] < d) continue;
        for(int i = head[u]; i; i = e[i].nxt){
            if(dist[e[i].v] > d + e[i].val){
                dist[e[i].v] = d + e[i].val;
                q.push(mk(dist[e[i].v], e[i].v));
            }
        }
    }
    for(int i = 1; i <= n; ++i) cout << dist[i] << " ";
    //cout << dist[n];
}

int main(){
    cin >> n >> m >> s;
    for(int i = 1, u, v, w; i <= m; ++i){
        cin >> u >> v >> w;
        add(u, v, w);
    }
    Dijkstra();
    return 0;
}

 

以上是关于Dijkstra的主要内容,如果未能解决你的问题,请参考以下文章

1.Dijkstra算法求解格栅地图路径matlab代码

1.Dijkstra算法求解格栅地图路径matlab代码

1.Dijkstra算法求解格栅地图路径matlab代码

计算图的最短距离--Dijkstra算法

如何将此代码从 Dijkstra 转换为 Astar?

java代码实现Dijkstra算法求图的最短路径