2024/2/18 图论 最短路入门 dijkstra 2

Dijkstra?

Problem - 20C - Codeforces

思路:

用dijkstra算法,在更新最短距离的时候在加一个存点的步骤,最后输出就可以了

p[i]是i的上一个点

完整代码:

cpp 复制代码
#include <bits/stdc++.h>
#define int long long
#define PII std::pair<int,int>
const int N = 1e5 + 10;
int p[N];
signed main() {
    int n, m;
    int k = 0;
    std::cin >> n >> m;
    std::vector<std::vector<PII>> g(n + 1);
    std::vector<int> dist(n + 1, LLONG_MAX);
    std::vector<bool> vis(n + 1);
    dist[1] = 0;
    for (int i = 1; i <= m; i++) {
        int u, v, w;
        std::cin >> u >> v >> w;
        g[u].push_back({v, w});
        g[v].push_back({u, w});
    }
    std::priority_queue<PII, std::vector<PII >, std::greater<>> q;
    q.push({0, 1});//存dist和点
    while (!q.empty()) {
        auto node = q.top();
        q.pop();
        int cur = node.second;
        if (vis[cur] == true)
            continue;
        vis[cur] = true;
        for (int i = 0; i < g[cur].size(); i++) {
            int e = g[cur][i].first;
            int w = g[cur][i].second;
            if (dist[e] > dist[cur] + w) {
                p[e] = cur;//从cur走到e
                dist[e] = dist[cur] + w;
                q.push({dist[e], e});
            }
        }
    }
    if(dist[n]==LLONG_MAX)
        std::cout<<-1;
    else {
        std::vector<int> a(n + 1);
        for (int i = n; i != 1; i = p[i]) {
            a[k++] = i;
        }
        std::cout << 1 << " ";
        for (int i = k - 1; i >= 0; i--) {
            std::cout << a[i] << " ";
        }
    }
//    std::cout<<dist[n];
    return 0;
}
相关推荐
归寻太乙5 分钟前
C++函数重载完成日期类相关计算
开发语言·c++
尽蝶叙7 分钟前
C++:分苹果【排列组合】
开发语言·c++·算法
所待.38314 分钟前
小小扑克牌算法
java·算法
憧憬成为原神糕手33 分钟前
c++_list
开发语言·c++
zyh2005043034 分钟前
c++的decltype关键字
c++·decltype
眰恦37442 分钟前
数据结构--第六章图
数据结构·算法
2401_862886781 小时前
蓝禾,汤臣倍健,三七互娱,得物,顺丰,快手,游卡,oppo,康冠科技,途游游戏,埃科光电25秋招内推
前端·c++·python·算法·游戏
luthane1 小时前
python 实现armstrong numbers阿姆斯壮数算法
python·算法
楠枬1 小时前
双指针算法
java·算法·leetcode