优化了一下之前写的dijkstra,使这段代码变得更好看()
#include <iostream>
#include <queue>
#include <algorithm>
#include <cstring>
using namespace std;
typedef pair<int, int> pii;
const int N = 2e5 + 10, INF = 0x3f3f3f3f;
int n, m;
int e[N], ne[N], h[N], w[N], d[N], idx;
bool st[N];
void intit() {
memset(h, -1, sizeof h);
memset(d, INF, sizeof d);
d[1] = 0;
}
void add(int a, int b, int c) {
w[idx] = c;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
int dijkstra() {
priority_queue<pii, vector<pii>, greater<>> q;
q.push({0, 1});
while (q.size()) {
pii t = q.top();
q.pop();
int p = t.second, dist = t.first;
if (st[p]) continue;
st[p] = true;
for (int i = h[p]; ~i ; i = ne[i]) {
int j = e[i];
if (d[j] > dist + w[i]) {
d[j] = w[i] + dist;
q.push({d[j], j});
}
}
}
return d[n] == INF ? -1 : d[n];
}
int main() {
cin >> n >> m;
intit();
while (m--) {
int a, b, c;
scanf("%d %d %d", &a, &b, &c);
add(a, b, c);
}
cout << dijkstra() << endl;
}