spfa求最短路
作者:
jy9
,
2024-07-31 11:28:19
,
所有人可见
,
阅读 2
完美
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
struct node{
int u, v;
};
int n, m;
const int N = 1e5+10;
vector<node> h[N];
int dist[N];
bool st[N];
void spfa(){
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
queue<int> q;
q.push(1);
st[1] = 1;
while(q.size()){
int t = q.front();
st[t] = 0;
q.pop();
for(auto [u, v]:h[t]){
if(dist[u] > dist[t]+v){
dist[u] = dist[t]+v;
if(st[u]) continue;
st[u] = 1;
q.push(u);
}
}
}
}
int main(){
int a, b, c;
cin >> n >> m;
for (int i = 1; i <= m; i ++ ){
cin >> a >> b >> c;
h[a].push_back({b, c});
}
spfa();
if(dist[n] == 0x3f3f3f3f) cout << "impossible";
else cout << dist[n];
return 0;
}