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

Dijkstra?

Problem - 20C - Codeforces

思路:

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

p[i]是i的上一个点

完整代码:

#include 
#define int long long
#define PII std::pair
const int N = 1e5 + 10;
int p[N];
signed main() {
    int n, m;
    int k = 0;
    std::cin >> n >> m;
    std::vector> g(n + 1);
    std::vector dist(n + 1, LLONG_MAX);
    std::vector 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, 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 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<

你可能感兴趣的:(寒假算法,寒假集训,图论,算法,数据结构,c++,c语言,dijkstra)