题目:
题解:
spfa模板
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int w[N],e[N],ne[N],h[N],dis[N],vis[N],idx;
int n,m;
typedef pair<int,int> pll;
int inf=0x3f3f3f3f;
void add(int a,int b,int c)
{
w[idx]=c;
e[idx]=b;
ne[idx]=h[a];
h[a]=idx++;
}
void spfa()
{
memset(dis,inf,sizeof(dis));
dis[1]=0;
queue<pll> q;
q.push({0,1});
vis[1]=1;
while(q.size())
{
pll k=q.front();
q.pop();
int t=k.second;
vis[t]=0;
for(int i=h[t];i!=-1;i=ne[i])
{
int j=e[i];
if(dis[j]>dis[t]+w[i])
{
dis[j]=dis[t]+w[i];
if(!vis[j])
{
vis[j]=1;
q.push({dis[j],j});
}
}
}
}
if(dis[n]==inf) cout<<"impossible"<<endl;
else cout<<dis[n]<<endl;
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof(h));
while(m--)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
spfa();
return 0;
}