AcWing 850. Dijkstra求最短路 II 堆优化版 优先队列 稀疏图
//稀疏图 点和边差不多 #include <cstring> #include <iostream> #include <algorithm> #include <queue> using namespace std; typedef pair<int, int> PII; const int N = 1e5 + 10; int n, m; int h[N], e[N], ne[N], idx; int w[N];//表示权值 int dist[N]; bool st[N]; void add(int a, int b, int c) { e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ; } int dijkstra() { memset(dist, 0x3f, sizeof dist); dist[1] = 0; priority_queue<PII, vector<PII>, greater<PII>> heap;//小根堆 heap.push({0, 1});//起点到起点的距离为0 while (heap.size()) { auto t = heap.top();//找到距离最小的点 heap.pop();//删掉 int ver = t.second, distance = t.first; if (st[ver]) continue;//如果这个点之前已经出来过,就跳过 st[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]; heap.push({dist[j], j}); } } } if (dist[n] == 0x3f3f3f3f) return -1; return dist[n]; } int main() { scanf("%d%d", &n, &m); memset(h, -1, sizeof h); while (m -- ) { int a, b, c; scanf("%d%d%d", &a, &b, &c); add(a, b, c); } cout << dijkstra() << endl; return 0; }