(蓝桥杯练习)道路和航路 Java---SPFA算法

本文探讨了一段Java代码,用于解决图的最短路径问题。通过邻接表表示图,作者分享了如何优化SPFA算法以在给定时间内达到更高的运行效率。对于有向和无向图的区别处理以及代码实现进行了深入剖析,寻求提高75分到满分的策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.*;

public class Main {
	//使用邻接表存图
    static class edge{
        int to;
        int val;
        public edge(int to, int val) {
            this.to = to;
            this.val = val;
        }
    }
    
    static List<edge>[] list;
    static int[] dis;
    static int INF = 0x3f3f3f3f;
    static int T,R,P,S;
    
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        T = sc.nextInt();
        R = sc.nextInt();
        P = sc.nextInt();
        S = sc.nextInt();
        list = new ArrayList[T];
        //设置标记,为true则存无向图,false存有向图
        boolean flag = false;
        for(int i = 0;i < R+P;i++){
            int s = 0;
            int y = 0;
            if(i < R){
                flag = true;
            }else{
                flag = false;
            }
            for(int j = 0;j<3;j++){
                int p = sc.nextInt();
                if (j == 0) {
                    s = p;
                } else if(j == 1){
                    y = p;
                }else {
                    if(list[s-1] == null){
                        list[s-1] = new ArrayList<>();
                    }
                    if(list[y-1] == null){
                        list[y-1] = new ArrayList<>();
                    }
                    list[s-1].add(new edge(y-1,p));
                    if(flag){
                        list[y-1].add(new edge(s-1,p));
                    }
                }
            }
        }
        spfa(S);
        for(int i = 0;i<T;i++){
            if(i == S-1){
                System.out.println(0);
            }else if(dis[i] == INF){
                System.out.println("NO PATH");
            }else {
                System.out.println(dis[i]);
            }
        }
    }
    //SPFA算法核心代码
    public static void spfa(int S){
        dis = new int[T];
        Arrays.fill(dis,INF);
        dis[S-1] = 0;
        Queue<Integer> q = new ArrayDeque<>();
        q.add(S-1);
        while(!q.isEmpty()){
            int a = q.poll();
            for(edge e : list[a]){
                if(dis[a] + e.val < dis[e.to]){
                    dis[e.to] = dis[a] + e.val;
                    q.add(e.to);
                }
            }
        }
    }
}

只跑了75分,不知如何优化,有跑满的大佬请在评论区分享您的代码(java)
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Uranus^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值