注意事项:
学习SPFA之前推荐先理解堆优化版的Dijkstra以及Bellman ford,并且涉及到邻接图用单链表数组模拟存储,之前写的文章链接:
java-单链表数组模拟
java-堆优化Dijkstra
java-Bellman ford
题目
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 impossible
数据保证不存在负权回路
第一行包含整数 n 和 m
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z
输入:
3 3
1 2 5
2 3 -3
1 3 4
输出:
2
public class 最短路_SPFA_存在负权边 {
//h,e,ne模拟邻接图,w存储边的权重,dist存储起点到当前节点的距离,st表示当前这个点是不是在队列当中,千万不要和dijkstra的st搞混了
public static int N = 1000010, index = 0, large = 0x3f3f3f3f, n, m;
public static int[] h = new int[N], e = new int[N], ne = new int[N], w = new int[N];
public static int[] dist = new int[N];
public static boolean[] st = new boolean[N];
public static void main(String[] args) {
//初始化,链表head全部为正无穷,n是点的个数,m是边的个数
Scanner in = new Scanner(System.in);
n = in.nextInt(); m = in.nextInt();
Arrays.fill(h, -1);
while (m-- > 0) {
int x = in.nextInt(), y = in.nextInt(), c = in.nextInt();
add(x, y, c);
}
SPFA();
}
//邻接表的插入操作,类似于单链表模拟
public static void add(int x, int y, int c) {
e[index] = y;
w[index] = c;
ne[index] = h[x];
h[x] = index++;
}
public static void SPFA() {
//还是最短路祖传的dist初始为正无穷,然后初始点到自己的距离为0
//然后q用来存储所有待更新的点,将起点推入队列,并且用st标记
Arrays.fill(dist, large);
dist[1] = 0;
Queue<Integer> q = new ArrayDeque<>();
q.add(1);
st[1] = true;
//和BFS宽搜有点类似,队列不空说明还有点没有进行更新,每次取出队列的头节点并用st标记为false,也就是队列中没有这个节点了
while (q.size() > 0) {
int t = q.poll();
st[t] = false;
//经典的单链表遍历,每次拿到节点j,如果(从起点到j点的距离)大于(从起点到t点的距离加上t点到j点的距离),那么就更新起点到j点的最短距离
//更新之后,如果j节点不在队列中,就将j加入到队列中,并用st标记
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.add(j);
st[j] = true;
}
}
}
}
//如果是正无穷说明从起点走不到n点
if (dist[n]==large) System.out.println("impossible");
else System.out.println(dist[n]);
}
}
理解Dijkstra和bellman ford之后,SPFA的写法也就大同小异了,没什么难理解的
最短路的解法选择以及时间复杂度:
声明:算法思路来源为y总,详细请见https://www.acwing.com/
本文仅用作学习记录和交流