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

Dijkstra?

Problem - 20C - Codeforces

思路:

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

pi是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;
}
相关推荐
计算机安禾7 小时前
【算法分析与设计】第46篇:近似难度与不可近似性理论
网络协议·算法·ssl
2023自学中7 小时前
Linux虚拟机 CMakeLists.txt:x86 与 ARM 双架构编译脚本
linux·c语言·c++·嵌入式
小bo波7 小时前
Java Swing 可视化素数筛:动态演示 1~120 质数筛选【附完整源码】
java·算法·可视化·swing·素数
眠りたいです7 小时前
现代C++:C++17中的新库特性
开发语言·c++·c++20·c++17
imDwAaY7 小时前
贝叶斯网络到粒子滤波Python算法实现 CS188 Proj4 学习笔记
网络·人工智能·笔记·python·学习·算法
sleven fung7 小时前
Whisper库
开发语言·人工智能·python·算法·ai·whisper
Black蜡笔小新7 小时前
自动化AI算法训练服务器DLTM零代码私有化一站式AI训练平台技术解析
人工智能·算法·自动化
天若有情6738 小时前
【C++趣味实战】仿写Burp代理逻辑!自定义可控迭代器:拦截Intercept/放行Forward/重放Repeater全实现
java·开发语言·c++
磊 子8 小时前
C++function与bind绑定器讲解
java·jvm·c++
梦想的颜色8 小时前
MySQL 查询性能核武器
运维·服务器·数据结构·数据库·mysql