【蓝桥杯】算法训练 最短路 JAVA

问题描述

给定一个n个顶点,m条边的有向图(其中某些边权可能为负,但保证没有负环)。请你计算从1号点到其他点的最短路(顶点从1到n编号)。

输入格式
第一行两个整数n, m。

接下来的m行,每行有三个整数u, v, l,表示u到v有一条长度为l的边。

输出格式
共n-1行,第i行表示1号点到i+1号点的最短路。
样例输入

3 3
1 2 -1
2 3 -1
3 1 2

样例输出

-1
-2

数据规模与约定
对于10%的数据,n = 2,m = 2。

对于30%的数据,n <= 5,m <= 10。

对于100%的数据,1 <= n <= 20000,1 <= m <= 200000,-10000 <= l <= 10000,保证从任意顶点都能到达其他所有顶点。

最短路模板题

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
	static int n,m;
	static int N=200010;
	static int[] h=new int[N];
	static int[] e=new int[N];
	static int[] ne=new int[N];
	static int[] w=new int[N];
	static int[] dist=new int[N];
	static boolean[] st=new boolean[N];
	static int INF=0x3f3f3f3f;
	static int idx=0;
	static void add(int a,int b,int c) {
		e[idx]=b;
		w[idx]=c;
		ne[idx]=h[a];
		h[a]=idx++;
	}
	
	static void spfa() {
		Arrays.fill(dist, INF);
		LinkedList<Integer> queue=new LinkedList<>();
		dist[1]=0;
		queue.push(1);
		st[1]=true;
		while (!queue.isEmpty()) {
			int t=queue.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]) {
						st[j]=true;
						queue.push(j);
					}
				}
			}
		}
	}
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
        String[] str1 = in.nextLine().split(" ");
        n = Integer.parseInt(str1[0]);
        m = Integer.parseInt(str1[1]);
        Arrays.fill(h, -1);
        while(m -- > 0)
        {
            String[] str2 = in.nextLine().split(" ");
            int a = Integer.parseInt(str2[0]);
            int b = Integer.parseInt(str2[1]);
            int c = Integer.parseInt(str2[2]);
            add(a,b,c);
        }
        spfa();
        for(int i=2;i<=n;i++) {
        	System.out.println(dist[i]);
        }
    }
	
	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蒙面侠1024

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

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

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

打赏作者

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

抵扣说明:

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

余额充值