题目地址:
https://www.acwing.com/problem/content/description/853/
给定一个 n n n个顶点 m m m条边的有向图,图中可能存在重边和自环, 边权可能为负数。求 1 1 1号点到 n n n号点的最短距离,如果无法从 1 1 1号点走到 n n n号点,则输出impossible。数据保证不存在负权回路。
输入格式:
第一行包含整数
n
n
n和
m
m
m。接下来
m
m
m行每行包含三个整数
x
x
x,
y
y
y,
z
z
z,表示存在一条从点
x
x
x到点
y
y
y的有向边,边长为
z
z
z。
输出格式:
输出一个整数,表示
1
1
1号点到
n
n
n号点的最短距离。如果路径不存在,则输出”impossible”。
数据范围:
1
≤
n
,
m
≤
1
0
5
1\le n,m\le 10^5
1≤n,m≤105
0
≤
∣
e
∣
≤
10000
0\le |e|\le 10000
0≤∣e∣≤10000
e
e
e为边长
可以用SPFA。它和Bellman-Ford算法类似,但是在进行更新操作的时候,它会开一个队列,并且只会把真实被更新为更短路的点进这个队列,以它来更新其它点(把未更新为更短路的点入队是没有意义的,因为它无法更新其它点)。同时,用一个数组来记录每个点是否在队列里,如果已经在队列里不用重复入队。代码如下:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 100010;
int n, m;
int h[N], w[N], e[N], ne[N], idx;
int dist[N];
// st[i]表示i这个点在队列里
bool st[N];
void add(int a, int b, int c) {
e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}
int spfa() {
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
queue<int> q;
q.push(1);
st[1] = true;
while (!q.empty()) {
int t = q.front();
q.pop();
// 出队了,就标记一下false
st[t] = false;
for (int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[t] + w[i]) {
dist[j] = dist[t] + w[i];
// 已经在队列里就不用重复入队了
if (!st[j]) {
q.push(j);
st[j] = true;
}
}
}
}
return dist[n] == 0x3f3f3f3f ? -1 : dist[n];
}
int main() {
cin >> n >> m;
memset(h, -1, sizeof h);
while (m--) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
int t = spfa();
if (t == -1) cout << "impossible" << endl;
else cout << t << endl;
return 0;
}
时间复杂度 O ( n m ) O(nm) O(nm)(但实际要比这个快很多),空间 O ( n + m ) O(n+m) O(n+m)。