目录
最短路问题
最短路问题---朴素Dijkstra算法,堆优化版Dijkstra算法,Bellman-Ford算法,SPFA算法,Floyd算法(算法思路+例题)_dijkstra+堆优化-CSDN博客
在这里,比较推荐SPFA算法。算法参考以上链接。
题目
解析
题目很明显,就是经典的最短路问题。只是多加了一个要隔离的时间,每次加上就好了,使用spfa算法
数组模拟邻接表+队列
时间复杂度:一般O(m) ,最坏O(nm)
伪代码:
Queue q
q <- 1
while(q不空)
t <- 取出q的队头
更新 t 的所有出边 t -> b
如果更新成功且 b 点没有在队列中 ,将 b 装入 q 中
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
//P8802 [蓝桥杯 2022 国 B] 出差
// SPFA
public class P8802 {
static int N = 20010;
static int n,m,idx;
// 数组模拟邻接表
static int[] h = new int[N];
static int[] e = new int[N];
static int[] ne = new int[N];
static int[] weight = new int[N]; // 每个城市隔离时间
static int[] weight1 = new int[N]; // 城市到城市之间的时间
static int[] dist = new int[N]; // 从1到每个点的最短距离
static boolean[] st = new boolean[N];
static Queue<Integer> q = new PriorityQueue<>();
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] s = in.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
// 读取隔离时间
s = in.readLine().split(" ");
for (int i = 1; i <= n; i++)
weight[i] = Integer.parseInt(s[i-1]);
// 初始化
Arrays.fill(h,-1);
Arrays.fill(dist,0x3f3f3f3f);
dist[1] = 0;
// 读取 m 个路径
for (int i = 0; i < m; i++) {
s = in.readLine().split(" ");
int a = Integer.parseInt(s[0]);
int b = Integer.parseInt(s[1]);
int c = Integer.parseInt(s[2]);
add(a,b,c);
add(b,a,c);
}
// spfa
q.add(1);
while (!q.isEmpty()){
int t = q.poll();
st[t] = false;
for (int i = h[t]; i != -1 ; i = ne[i]) {
int j = e[i];
int w = weight1[i];
int c = weight[j];
if(dist[j]>dist[t]+c+w){
dist[j] = dist[t]+c+w;
if(!st[j]){
q.add(j);
st[j] = true;
}
}
}
}
System.out.println(dist[n]-weight[n]); // n不隔离
}
public static void add(int a,int b,int c){
weight1[idx] = c;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
}