P8802 [蓝桥杯 2022 国 B] 出差——最短路问题(SPFA)

目录

题目

解析

代码


最短路问题

最短路问题---朴素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++;
    }
}

  • 16
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值