原题链接
①. 题目
②. 思路
- 适用范围:只要没有负环,都可以使用。
- spfa也能解决权值为正的图的最短距离问题,且一般情况下比Dijkstra算法还好
queue <– 1
while queue 不为空
(1) t <– 队头
queue.pop()
(2)用 t 更新所有出边 t –> b,权值为w
queue <– b (若该点被更新过,则拿该点更新其他点)
1. 初始化dist[1]=0; dist[其他点] = 正无穷
2. 队列不空
1. 只有这个点被更新后,其他与它相连的点才会被更新
③. 学习点
spfa算法
④. 代码实现
import java.util.*;
public class Main {
static int N=100010;
static int n,m;
static int h[]=new int[N],e[]=new int[N],ne[]=new int[N],w[]=new int[N];
static int idx;
static int[] dist=new int[N];
static boolean[] st=new boolean[N];
static int INF=0x3f3f3f3f;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n=sc.nextInt();
m=sc.nextInt();
Arrays.fill(h, -1);
while (m-- > 0) {
int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();
add(a, b, c);
}
int res = spfa();
if (res == -1) System.out.println("impossible");
else System.out.println(res);
}
static void add(int a,int b,int c) {
e[idx]=b;
ne[idx]=h[a];
w[idx]=c;
h[a]=idx++;
}
static int spfa() {
Arrays.fill(dist, INF);
Queue<Integer> q=new LinkedList<>();
q.offer(1);
dist[1]=0;
while(!q.isEmpty()) {
int t=q.poll();
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.offer(j);
st[j]=true;
}
}
}
}
if(dist[n]==INF) {
return -1;
}
return dist[n];
}
}