spfa算法
作者:
Qjwwww
,
2022-04-08 09:50:15
,
所有人可见
,
阅读 311
//spfa算法求单源最短路,能解决负权问题
//背模板
#include<bits/stdc++.h>
using namespace std;
int n,m;
#define inf 0x7ffffff
const int N = 100010;
int h[N],to[N],w[N],nxt[N];
int cnt;
int dist[N],vis[N];
void addedge(int a,int b,int val)
{
nxt[++cnt] = h[a];
h[a] = cnt;
to[cnt] = b;
w[cnt] = val;
}
void spfa()
{
for(int i=1;i<=n;i++) dist[i] = inf;
dist[1] = 0;
queue<int> q;
q.push(1);
vis[1] = 1;
while(!q.empty())
{
int now = q.front();
q.pop();
vis[now] = 0;
for(int i=h[now];i;i=nxt[i])
{
int j = to[i];
if(dist[j]>dist[now] + w[i])
{
dist[j] = dist[now] + w[i];
if(vis[j]==0)
{
q.push(j);
vis[j] = 1;
}
}
}
}
}
int main()
{
cin>>n>>m;
int x,y,z;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z);
}
spfa();
if(dist[n]==inf) cout<<"impossible";
else cout<<dist[n];
return 0;
}