850. Dijkstra求最短路 II (堆优化 + 邻接表)

跳转链接

https://www.acwing.com/problem/content/856/ 来源:模板题

题目描述

给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为非负值。 请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。

输入格式 第一行包含整数 n 和 m。 接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。 输出格式 输出一个整数,表示 1 号点到 n 号点的最短距离。 如果路径不存在,则输出 −1。 数据范围 1 nn,mm 1.5×10^5^, 图中涉及边长均不小于 0,且不超过 10000。 数据保证:如果最短路存在,则最短路的长度不超过 10^9^。 输入样例
3 3 1 2 2 2 3 1 1 3 4 输出样例 impossible 3

题解思路

参考https://www.acwing.com/solution/content/14007/ (含具体注释)

代码

cpp
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 150010;

int n, m, a, b, c, idx;
int h[N], e[N], ne[N], w[N], dist[N];
bool vis[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

int dijkstra()
{
    priority_queue<PII, vector<PII>, greater<PII> >q;  //改为小根堆存储
    memset(dist, 0x3f, sizeof dist);  // 不能忘了初始化具体
    dist[1] = 0;
    q.push({0, 1});  // 这个顺序不能倒,pair排序时是先根据first,再根据second,这里显然要根据距离排序
    
    while (q.size())
    {
        auto t = q.top();
        q.pop();
        
        int ver = t.second, distance = t.first;
        if (vis[ver])   continue;
        vis[ver] = true;
        
        for (int i = h[ver]; i != -1; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > distance + w[i])   
            {
                dist[j] = distance + w[i];
                q.push({dist[j], j});
            }
        }
    }
    if (dist[n] == 0x3f3f3f3f)  return -1;
    return dist[n];
}


int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> m;
    
    while (m--)
    {
        cin >> a >> b >> c;
        add(a, b, c); 
    }
    
    int t = dijkstra();
    cout << t;
    return 0;
}
853. 有边数限制的最短路 题解
854. Floyd求最短路 题解
Valaxy v1.0.0-rc.3 驱动|主题-Yunv1.0.0-rc.3