Dijkstra算法代码

随便记一下

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <climits>

using namespace std;

//2021-3-19 11:31
//Dijkstra算法求单源最短路径

const int MAXN = 200;
const int INF = INT_MAX;

struct Edge {
    int to;     //边终点
    int length;     //边长度
    Edge(int t, int l) : to(t), length(l) {}
};

struct Point {
    int number;     //点编号
    int distance;       //源点到该点距离
    Point(int n, int d) : number(n), distance(d) {}
    bool operator< (const Point& p) const {
        return distance > p.distance;
    }
};

vector<Edge> graph[MAXN];
int dis[MAXN];

void Dijkstra(int s) {
    dis[s] = 0;
    priority_queue<Point> mypriorityqueue;
    mypriorityqueue.push(Point(s, dis[s]));
    while (!mypriorityqueue.empty()) {
        int u = mypriorityqueue.top().number;
        mypriorityqueue.pop();
        for (int i = 0; i < graph[u].size(); ++i) {
            int v = graph[u][i].to;
            int d = graph[u][i].length;
            if (dis[v] > dis[u] + d) {
                dis[v] = dis[u] + d;
                mypriorityqueue.push(Point(v, dis[v]));
            }
        }
    }
    return;
}

int main() {
    int n, m;
    while (scanf("%d%d", &n, &m) != EOF) {
        memset(graph, 0, sizeof(graph));
        fill(dis, dis + n, INF);
        while (m--) {
            int from, to, length;
            scanf("%d%d%d", &from, &to, &length);
            graph[from].push_back(Edge(to, length));
            graph[to].push_back(Edge(from, length));
        }
        int s, t;
        scanf("%d%d", &s, &t);
        Dijkstra(s);
        if (dis[t] == INF) {
            dis[t] = -1;
        }
        printf("%d\n", dis[t]);
    }
    return 0;
}
全部评论

相关推荐

一名愚蠢的人类:多少games小鬼留下了羡慕的泪水
投递荣耀等公司10个岗位
点赞 评论 收藏
分享
我见java多妩媚:大外包
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务