AcWing853-有边数限制的最短路(java实现)

本文详细介绍了AcWing853题目,该题目要求在有向图中寻找从1号点到n号点最多经过k条边的最短路径,允许存在负权边和负权回路。通过Bellman-Ford算法实现,当最短距离超过一定阈值时输出'Impossible'。示例展示了输入输出格式及代码实现。

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

AcWing853-有边数限制的最短路

题目描述

给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环, 边权可能为负数

请你求出从 1 号点到 n 号点的最多经过 kk 条边的最短距离,如果无法从 1 号点走到 n 号点,输出 impossible

注意:图中可能 存在负权回路

输入格式

第一行包含三个整数 n,m,k。

接下来 m 行,每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。

输出格式

输出一个整数,表示从 1 号点到 n 号点的最多经过 k 条边的最短距离。

如果不存在满足条件的路径,则输出 impossible

数据范围

1≤n,k≤500
1≤m≤10000
任意边长的绝对值不超过 10000。

输入样例:

3 3 1
1 2 1
2 3 1
1 3 3

输出样例:

3

题解

package acWing853;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
class Node{
    int a, b, c;
    public Node(int a,int b,int c)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}
public class Main {
    static int N = 510,M = 100010;
    static int n,m,k;
    static int[] dist = new int[N];	//	从1到点到n号点的距离
    static Node[] list = new Node[M];
    static int INF = 0x3f3f3f3f;
    static int[] back = new int[N];	//	备份dist数组
    
    public static void bellman_ford(){
        Arrays.fill(dist, INF);
        dist[1] = 0;
        for(int i = 0;i < k;i++){
            back = Arrays.copyOf(dist, n + 1);	//	由于是从1开始存到n
            for(int j = 0;j < m;j++){
                Node node = list[j];
                int a = node.a,b = node.b, c = node.c;
                dist[b] = Math.min(dist[b], back[a] + c);
            }
        }
        System.out.println(dist[n] > INF/2 ? "impossible":dist[n]);
    }
    
    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String[] str = bf.readLine().split(" ");
        n = Integer.parseInt(str[0]);m = Integer.parseInt(str[1]);k = Integer.parseInt(str[2]);
        for(int i = 0;i < m;i++){
            str = bf.readLine().split(" ");
            int a = Integer.parseInt(str[0]),b = Integer.parseInt(str[1]),c = Integer.parseInt(str[2]);
            list[i] = new Node(a,b,c);
        }
        bellman_ford();
        bf.close();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

杜柠函

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

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

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

打赏作者

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

抵扣说明:

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

余额充值