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;
}
相关推荐
Zero不爱吃饭几秒前
环形链表(C)
数据结构·链表
xiaoye-duck1 分钟前
数据结构之二叉树-链式结构(下)
数据结构·算法
Kt&Rs4 分钟前
11.13 LeetCode 题目汇总与解题思路
数据结构·算法
大锦终4 分钟前
【Linux】高级IO
linux·服务器·网络·c++
灵晔君13 分钟前
C++标准模板库(STL)——list的使用
c++·list
努力学习的小廉28 分钟前
我爱学算法之—— 字符串
c++·算法
yuuki2332331 小时前
【数据结构】常见时间复杂度以及空间复杂度
c语言·数据结构·后端·算法
闻缺陷则喜何志丹1 小时前
【分块 差分数组 逆元】3655区间乘法查询后的异或 II|2454
c++·算法·leetcode·分块·差分数组·逆元
葛小白11 小时前
C#进阶12:C#全局路径规划算法_Dijkstra
算法·c#·dijkstra算法
前端小L1 小时前
图论专题(五):图遍历的“终极考验”——深度「克隆图」
数据结构·算法·深度优先·图论·宽度优先