1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <algorithm> #include <iostream> #include <cstring> #include <queue> using namespace std; typedef long long LL;
const int N = 1000010; int h[N], e[N], ne[N], w[N]; int idx, n, m; int d[N]; bool vis[N]; typedef pair<int, int> PII;
void insert(int a, int b, int c) { e[idx] = b; ne[idx] = h[a]; w[idx] = c; h[a] = idx++; }
int dijkstra() { priority_queue<PII, vector<PII>, greater<PII>> qu; qu.push({ 0,1 }); memset(d, 0x3f, sizeof d); d[1] = 0;
while (qu.size()) { auto t = qu.top(); qu.pop(); int dis = t.first, ver = t.second; if (vis[ver]) continue; vis[ver] = true;
for (int i = h[ver]; ~i; i = ne[i]) { int vv = e[i]; if (d[vv] > d[ver] + w[i]) { d[vv] = d[ver] + w[i]; qu.push({ d[vv], vv }); } } } if (d[n] == 0x3f3f3f3f) return -1; return d[n]; }
int main() { cin >> n >> m; int a, b, c;
memset(h, -1, sizeof(h));
while (m--) { cin >> a >> b >> c; insert(a, b, c); }
cout << dijkstra(); return 0; }
|