AcWing 851. spfa求最短路
原题链接
简单
作者:
啊_45
,
2021-04-29 18:48:44
,
所有人可见
,
阅读 180
#include <bits/stdc++.h>
using namespace std;
int n,m;
const int N = 1e5+10;
int e[N],h[N],ne[N],idx,w[N];
int dist[N],st[N];
void add(int a,int b,int c)
{
e[idx] = b,ne[idx] = h[a],w[idx] = c,h[a] = idx++;
}
int spfa()
{
memset(dist,0x3f,sizeof dist);
dist[1] = 0;
st[1] = true;
queue<int> q;
q.push(1);
while(!q.empty())
{
int t = q.front();
q.pop();
st[t] =false;
for(int i=h[t] ;i!=-1;i=ne[i])
{
int j =e[i];
if(dist[j]>dist[t] + w[i])
{
dist[j] =dist[t] +w[i];
if(!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return dist[n];
}
int main()
{
memset(h,-1,sizeof h);
cin>>n>>m;
while( m -- )
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
int t = spfa();
if(t == 0x3f3f3f3f)
cout<<"impossible";
else
cout<<t;
}