代码LGD

该文章详细描述了如何在C++中实现Dijkstra算法,用于寻找有向图中的最短路径,包括输入数据结构、算法步骤和路径回溯部分。
摘要由CSDN通过智能技术生成

#include <iostream>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>

using namespace std;

const int INF = INT_MAX;

struct Edge {
    int to;
    int len;
};

void dijkstra(vector<vector<Edge>>& graph, vector<int>& dist, vector<int>& prev, int start) {
    int n = graph.size();
    dist[start] = 0;
    prev[start] = -1;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
    pq.push({0, start});

    while (!pq.empty()) {
        int u = pq.top().second;
        pq.pop();

        for (const auto& edge : graph[u]) {
            int v = edge.to;
            int len = edge.len;

            if (dist[u] + len < dist[v]) {
                dist[v] = dist[u] + len;
                prev[v] = u;
                pq.push({dist[v], v});
            }
        }
    }
}

vector<int> getShortestPath(vector<int>& prev, int end) {
    vector<int> path;
    while (end != -1) {
        path.push_back(end);
        end = prev[end];
    }
    reverse(path.begin(), path.end());
    return path;
}

int main() {
    int n, m, s, t;
    cin >> n >> m >> s >> t;

    vector<vector<Edge>> graph(n + 1);
    for (int i = 0; i < m; i++) {
        int x, y, len;
        cin >> x >> y >> len;
        graph[x].push_back({y, len});
        graph[y].push_back({x, len});
    }

    vector<int> dist(n + 1, INF);
    vector<int> prev(n + 1, -1);

    dijkstra(graph, dist, prev, s);

    if (dist[t] == INF) {
        cout << "can't arrive" << endl;
    } else {
        cout << dist[t] << endl;
        vector<int> path = getShortestPath(prev, t);
        for (int i = 0; i < path.size(); i++) {
            cout << path[i] << " ";
        }
        cout << endl;
    }

    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值