spfa旧事重提
作者:
jy9
,
2024-10-03 18:50:44
,
所有人可见
,
阅读 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[0] = 1;
while(q.size()){
int t = q.front();
q.pop();
st[t] = 0;
for(auto [u, v]:h[t]){
if(dist[u] > dist[t] + v){
dist[u] = dist[t] + v;
if(st[u]) continue;
q.push(u);
st[u] = 1;
}
}
}
}
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;
}