spfa 求最短路
题目描述
给定一个 n 个点 m 条边的有向图,图中可能存在 重边 和 自环 , 边权可能为 负数 。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 impossible
。
数据保证不存在负权回路。
输入格式
第一行包含整数 n 和 m。
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
如果路径不存在,则输出 impossible
。
数据范围
1
≤
n
,
m
≤
1
0
5
1≤n,m≤10^5
1≤n,m≤105,
图中涉及边长绝对值均不超过
10000
10000
10000。
输入样例:
3 3
1 2 5
2 3 -3
1 3 4
输出样例:
2
Java spfa
import java.util.*;
class Main{
static int N = 100010, INF = 0x3f3f3f3f;
static int n, m , d[] = new int[N];
static int h[] = new int[N], e[] = new int[N], ne[] = new int[N], w[] = new int[N], idx;
static boolean st[] = new boolean[N];
static void add(int a, int b, int c){
e[idx] = b; w[idx] = c; ne[idx] = h[a]; h[a] = idx ++;
}
static int spfa(){
Arrays.fill(d, Integer.MAX_VALUE);
d[1] = 0;
Queue<Integer> q = new LinkedList<Integer>();
q.offer(1);
while (q.size() > 0){
int t = q.poll();
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.offer(j);
st[j] = true;
}
}
}
}
if (d[n] > INF / 2) return INF;
else return d[n];
}
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, b, c;
a = sc.nextInt(); b = sc.nextInt(); c = sc.nextInt();
add(a, b, c);
}
int res = spfa();
if (res == INF) System.out.println("impossible");
else System.out.println(res);
sc.close();
}
}
spfa作为最基本的图论算法值得大家掌握和进行学习