SPFA求最短路
作者:
amagi
,
2023-07-17 12:21:54
,
所有人可见
,
阅读 93
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100001;
int ne[N],e[N],h[N],w[N],idx;
int dis[N];
bool p[N];
int n,m;
void add(int a,int b,int c){
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx ++;
}
int spa(){
queue<int> qq;
memset(dis,0x3f,sizeof dis);
dis[1] = 0;
p[1] = true;
qq.push(1);
while(qq.size()){
auto f = qq.front();
qq.pop();
p[f] = false;
for(int i = h[f]; i != -1; i = ne[i]){
int j = e[i];
if(dis[j] > dis[f] + w[i]){
dis[j] = dis[f] + w[i];
if(p[j] == false){
p[j] = true;
qq.push(j);
}
}
}
}
return dis[n];
}
int main(){
cin >> n >> m;
memset(h,-1,sizeof h);
for(int i = 1; i <= m; i ++){
int a,b,c;
cin >> a >> b >> c;
add(a,b,c);
}
int res = spa();
if(res >= 0x3f3f3f) cout << "impossible" << endl;
else cout << res << endl;
}