#include<bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
const int N = 1e6 + 100;
int h[N], ne[N], w[N], e[N], idx, dis[N], st[N];
int n, m;
void add(int a, int b, int c)
{
w[idx] = c;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx ++;
}
int spfa()
{
memset(dis, 0x3f, sizeof dis);
queue<int> Q;
Q.push(1);
st[1] = 1;
dis[1] = 0;
while(Q.size())
{
int head = Q.front();
Q.pop();
st[head] = 0;
for(int j = h[head]; ~j; j = ne[j])
{
int x = e[j];
if(dis[x] > dis[head] + w[j])
{
dis[x] = dis[head] + w[j];
if(st[x] == 0)
{
Q.push(x);
st[x] = 1;
}
}
}
}
if(dis[n] > inf / 2) return -1; //dis[n] 大于 inf/2 说明没有路径
else return dis[n];
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for(int i = 0; i < m; i ++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
int t = spfa();
if(t == -1) puts("impossible");
else cout << dis[n];
spfa求最短路径
最新推荐文章于 2023-02-15 11:11:44 发布