Dijkstra求最短路 I
给定一个n个点m条边的有向图,图中可能存在重边和自环,所有边权均为正值。
请你求出1号点到n号点的最短距离,如果无法从1号点走到n号点,则输出-1。
输入格式
第一行包含整数n和m。
接下来m行每行包含三个整数x,y,z,表示存在一条从点x到点y的有向边,边长为z。
输出格式
输出一个整数,表示1号点到n号点的最短距离。
如果路径不存在,则输出-1。
数据范围
1≤n≤500,
1≤m≤105,
图中涉及边长均不超过10000。
输入样例:
3 3
1 2 2
2 3 1
1 3 4
输出样例:
3
C++ 代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <functional>
using namespace std;
/*
避免使用 邻接表 存储拓扑信息;
注意事项:
1. 记录 起始点的数个出边,以便查询最短距离,
这是Dijkstra算法的核心了。
2.
*/
typedef pair<int, int> PII; //<离起点的距离, 节点编号>
#define dists first
#define index second
const int N = 150010;
const int Inf = 0x3f3f3f3f;
/*
idx: 边的序号
h[node]:以 node点 为起点的最后一条边
e:边的终止结点序号
ne[idx]:与 边idx 同起始结点的下一条边的序号
w: 边的权重
dist:到源点的距离
*/
int h[N], e[N], ne[N], idx = 0, w[N];
int dist[N];
bool vst[N];
int n, m;
//在a节点之后插入一个b节点,权重为c
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>> nodes;
memset(dist, 0x3f, sizeof(dist));
memset(vst, false, sizeof(vst));
// 待处理节点 : 源点
dist[1] = 0;
nodes.push({ 0, 1 });
while (nodes.size()) {
PII node = nodes.top();
nodes.pop();
int nIdx = node.index;
int nDst = node.dists;
// 选择未访问过的结点
if (vst[nIdx])
continue;
vst[nIdx] = true;
// 逐个处理 当前节点发出的边 可以到达的终点结点
for (int i = h[nIdx]; i != -1; i = ne[i]) {
int eNode = e[i];
if (dist[eNode] > nDst + w[i]) {
dist[eNode] = nDst + w[i];
nodes.push({ dist[eNode], eNode });
}
}
}
// 初始化值未被更新
if (dist[n] == 0x3f3f3f3f)
return -1;
return dist[n];
}
int main() {
memset(h, -1, sizeof(h));
memset(w, 0, sizeof(w));
memset(e, 0, sizeof(e));
memset(ne, 0, sizeof(ne));
cin >> n >> m;
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
cout << dijkstra() << endl;
return 0;
}