SPFA
使用队列来保存更新过的顶点(栈或者优先队列也可以)。只有更新过的顶点才会产生松弛操作。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <queue>
#include <unordered_map>
using namespace std;
const int N = 100010;
const int INF = 0x3f3f3f3f;
int n, m;
int d[N];
bool st[N]={false};
int idx = 0 ;
int h[N], ne[N], e[N], w[N]; //邻接表
void add(int a, int b, int c){
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++; //其实是倒着遍历的 类似于链串起来,然后倒着查回去
}
int spfa(int s){
memset(d, 0x3f, sizeof d);
d[s] = 0;
queue<int> q;
q.push(1);
st[1] = true;
while(q.size()){
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t]; i != -1; i = ne[i]){
int j = e[i];
if(d[j] > d[t]+ w[i]){
d[j] = d[t]+ w[i];
if(!st[j]){
q.push(j);
st[j] = true;
}
}
}
}
if(d[n] == 0x3f3f3f3f) return -1;
else return d[n];
}
int main(){
scanf("%d%d", &n, &m);
int u, v, w;
memset(h, -1, sizeof h);
for(int i = 0; i < m; i++){
scanf("%d%d%d", &u, &v, &w);
add(u, v, w); //重边 自环都没影响
}
int t = spfa(1);
if(t==-1) puts("impossible");
else printf("%d\n", t);
return 0;
}