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;
}
相关推荐
heimeiyingwang9 天前
【深度学习加速探秘】Winograd 卷积算法:让计算效率 “飞” 起来
人工智能·深度学习·算法
LyaJpunov9 天前
深入理解 C++ volatile 与 atomic:五大用法解析 + 六大高频考点
c++·面试·volatile·atomic
小灰灰搞电子9 天前
Qt PyQt与PySide技术-C++库的Python绑定
c++·qt·pyqt
时空自由民.9 天前
C++ 不同线程之间传值
开发语言·c++·算法
ai小鬼头9 天前
AIStarter开发者熊哥分享|低成本部署AI项目的实战经验
后端·算法·架构
小白菜3336669 天前
DAY 37 早停策略和模型权重的保存
人工智能·深度学习·算法
zeroporn9 天前
以玄幻小说方式打开深度学习词嵌入算法!! 使用Skip-gram来完成 Word2Vec 词嵌入(Embedding)
人工智能·深度学习·算法·自然语言处理·embedding·word2vec·skip-gram
Ray_19979 天前
C++二级指针的用法指向指针的指针(多级间接寻址)
开发语言·jvm·c++
亮亮爱刷题9 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
_周游9 天前
【数据结构】_二叉树OJ第二弹(返回数组的遍历专题)
数据结构·算法