Dijkstra

Posted hkttg

tags:

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

ddd

ddd

#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#include<iostream>
#define MAXN 500010
#define oo 2147483647

using namespace std;

int head[MAXN * 2],dis[MAXN],tot,n,m,s;
bool vis[MAXN];

typedef pair<int, int> pir;

struct Edge {
    int node;
    int next;
    int value;
}e[MAXN];

inline void add(int x,int y,int z) {
    e[++tot].node = y; e[tot].value = z; e[tot].next = head[x]; head[x] = tot;
}

priority_queue<pir, vector<pir>, greater<pir> > que;

void dijkstra(int s) {
    dis[s] = 0;
    que.push(make_pair(dis[s], s));
    while (!que.empty()) {
        pir temp = que.top();
        que.pop();
        int x = temp.second;
        if (!vis[x]) {
            vis[x] = true;
            for (int i = head[x]; i ; i = e[i].next) {
                int v = e[i].node;
                if (dis[v] > dis[x] + e[i].value) {
                    dis[v] = dis[x] + e[i].value;
                    que.push(make_pair(dis[v],v));
                }
            }
        }
    }
}

inline int read() {
    int num = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == -) f = -1;
        ch = getchar(); 
    }
    while (isdigit(ch)) {
        num = num * 10 + ch - 0;
        ch = getchar();
    }
    return num * f;
}

int main() {
    n = read(); m = read(); s = read();
    for (int i = 1; i <= m; i++) {
        int x,y,z;
        x = read(); y = read(); z = read();
        add(x,y,z);
    }
    for (int i = 1; i <= n; i++) dis[i] = oo;
    dijkstra(s);
    for (int i = 1; i <= n; i++)
        printf("%d ",dis[i]);
    return 0;
} 

 

ddd

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

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

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

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

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

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

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