Java spfa求最短路

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 1n,m105,
图中涉及边长绝对值均不超过 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作为最基本的图论算法值得大家掌握和进行学习

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值