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.

56 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
const int N = 100010, M = 2 * N;
const int INF = 0x3f3f3f3f;
using namespace std;
int n, m; // 总点数
int d[N]; // 存储每个点到1号点的最短距离
int st[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++;
}
// 求1号点到n号点的最短路距离如果从1号点无法走到n号点则返回-1
void spfa(int s) {
// 初始化距离
memset(d, 0x3f, sizeof d);
d[s] = 0;
queue<int> q;
q.push(s);
st[s] = 1;
while (q.size()) {
int u = q.front();
q.pop();
st[u] = 0;
for (int i = h[u]; ~i; i = ne[i]) {
int v = e[i];
if (d[v] > d[u] + w[i]) {
d[v] = d[u] + w[i];
// 如果队列中已存在v则不需要将v重复插入,优化一下
if (!st[v]) {
q.push(v);
st[v] = 1;
}
}
}
}
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> m;
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
spfa(1);
if (d[n] == INF)
puts("impossible");
else
printf("%d\n", d[n]);
return 0;
}