spfa是bellman——ford的队列优化版本,通过bfs:
优化的是dist[b] = min(dist[b], dist[a]+w)
因为只有dist[a]更新之后变小, dist[b]更新之后才有可能变小
需要st[i]数组,保证队列里面只有一个i;
给定一个 nn 个点 mm 条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你求出 11 号点到 nn 号点的最短距离,如果无法从 11 号点走到 nn 号点,则输出 impossible
。
数据保证不存在负权回路。
输入格式
第一行包含整数 nn 和 mm。
接下来 mm 行每行包含三个整数 x,y,zx,y,z,表示存在一条从点 xx 到点 yy 的有向边,边长为 zz。
输出格式
输出一个整数,表示 11 号点到 nn 号点的最短距离。
如果路径不存在,则输出 impossible
。
数据范围
1≤n,m≤1051≤n,m≤105,
图中涉及边长绝对值均不超过 1000010000。
输入样例:
3 3
1 2 5
2 3 -3
1 3 4
输出样例:
2
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 1e05+ 10;
int read(){
int res = 0 , flag = 1 ;
char c = getchar() ;
while(!isdigit(c)){
if(c == '-') flag = -1 ;
c = getchar() ;
}
while(isdigit(c)){
res = (res << 1) + (res << 3) + (c ^ 48) ;
c = getchar() ;
}
return res * flag ;
}
int ne[N], h[N], e[N], w[N], idx;
bool st[N];
int dist[N];
int n, m;
queue<int> q;
void add(int a, int b, int c) {
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx ++;
}
int spfa() {
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
q.push(1);
st[1] = true;
while (q.size()) {
int u = q.front();
q.pop();
st[u] = false;
for (int i = h[u]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[u] + w[i]) {
dist[j] = dist[u] + w[i];
if(!st[j]) {
st[j] = true;
q.push(j);
}
}
}
}
return dist[n];
}
int main() {
memset(h, -1, sizeof h);
n = read();
m = read();
while (m --) {
int a, b, c;
a = read();
b = read();
c = read();
add(a, b, c);
}
int res = spfa();
if (res == 0x3f3f3f3f) puts("impossible");
else cout << res << endl;
return 0;
}