#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
const int N = 100010;
int n, m;//n个点,m个边
int h[N], w[N], e[N], ne[N], idx;//队列
int dist[N];//距离
bool st[N];//这个比较重要,与dijkstra不一样,用于判断该数字是否已经进过队列,因为这次队列里面只存点的序号,所以每个点只进一次
void add(int a, int b, int c)
{
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}
int spfa()
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
queue<int> q;//队列只进点
q.push(1);
st[1] = true;//进一个点,将该点设为true
while (q.size())
{
int t = q.front();//就是按顺序拿出来,不考虑大小
q.pop();
st[t] = false;//更新状态
for (int i = h[t]; i != -1; i = ne[i])//这里是对所有和t直接连接的数字判断三角形
{
int j = e[i];
if (dist[j] > dist[t] + w[i])//只有dist更新了才会考虑是否将j放入
{
dist[j] = dist[t] + w[i];
if (!st[j])//如果j已经存在,不用放入,防止重复
{
q.push(j);
st[j] = true;//更新状态
}
}
}
}
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);
}
int t = spfa();
if (t == 0x3f3f3f3f) puts("impossible");//不能用t==-1判断,因为距离可能为-1
else printf("%d\n", t);
return 0;
}
与dijkstra不同的地方是,spfa不能每次拿出剩下没确定的数作为确定值去更新其他值,spfa是从开始的点到起始点能直接连接的每个点判断三角形,只有当dist被更新(说明到这个点了)才将这个点放入队列中(放入的都是dist不为无穷大的)。
然后直到队列为空退出,即所有点的dist都被更新完。
注意:不到所有点更新完,没有一个点的dist是确定的