You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.2 KiB
52 lines
1.2 KiB
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
typedef pair<int, int> PII;
|
|
const int INF = 0x3f3f3f3f;
|
|
const int N = 150010, M = N << 1;
|
|
|
|
int st[N];
|
|
int dis[N]; // 距离数组
|
|
|
|
// 邻接表
|
|
int e[M], h[N], idx, w[M], ne[M];
|
|
void add(int a, int b, int c) {
|
|
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
|
|
}
|
|
|
|
int n, m;
|
|
int dijkstra() {
|
|
memset(dis, 0x3f, sizeof dis);
|
|
dis[1] = 0;
|
|
priority_queue<PII, vector<PII>, greater<PII>> q; // 小顶堆
|
|
q.push({0, 1});
|
|
|
|
while (q.size()) {
|
|
PII t = q.top();
|
|
q.pop();
|
|
int u = t.second;
|
|
if (!st[u]) {
|
|
st[u] = 1;
|
|
for (int i = h[u]; ~i; i = ne[i]) {
|
|
int v = e[i];
|
|
if (dis[v] > dis[u] + w[i]) {
|
|
dis[v] = dis[u] + w[i];
|
|
q.push({dis[v], v});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (dis[n] == INF) return -1;
|
|
return dis[n];
|
|
}
|
|
int main() {
|
|
cin >> n >> m;
|
|
memset(h, -1, sizeof h);
|
|
while (m--) {
|
|
int a, b, c;
|
|
cin >> a >> b >> c;
|
|
add(a, b, c);
|
|
}
|
|
printf("%d\n", dijkstra());
|
|
return 0;
|
|
} |