1268: 单源最短路径问题

1268: 单源最短路径问题

时间限制: 1 Sec  内存限制: 128 MB
提交: 86  解决: 45
[提交] [状态] [讨论版] [命题人:外部导入]

题目描述

给你一个n(1<=n<=2500)个点m(1<=m<=6200)条边的无向图,求s到t的最短路

输入

第一行四个由空格隔开的整数n,m,s,t
之后的m行,每行三个正整数u,v,w(1<=w<=1e9),表示一条从u到v长度为w的边

输出

一个整数表示从s到t的最短路长度。数据保证至少存在一条道路

样例输入 Copy
7 11 5 4
2 4 2
1 4 3
7 2 2
3 4 3
5 7 5
7 3 3
6 1 1
6 3 4
2 4 3
5 6 3
7 2 1
样例输出 Copy
7
来源/分类

分支限界法

import java.util.*;
//1268
class Edge {
    int to;
    int weight;
 
    public Edge(int to, int weight) {
        this.to = to;
        this.weight = weight;
    }
}
 
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt(); // 点的数量
        int m = scanner.nextInt(); // 边的数量
        int s = scanner.nextInt(); // 起点
        int t = scanner.nextInt(); // 终点
 
        List<List<Edge>> graph = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            graph.add(new ArrayList<>());
        }
 
        // 构建图的邻接表表示
        for (int i = 0; i < m; i++) {
            int u = scanner.nextInt();
            int v = scanner.nextInt();
            int w = scanner.nextInt();
            graph.get(u - 1).add(new Edge(v - 1, w));
            graph.get(v - 1).add(new Edge(u - 1, w));
        }
 
        int[] distance = new int[n]; // 起点到各点的最短距离数组
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[s - 1] = 0;
 
        // 使用Dijkstra算法求解最短路径
        PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> distance[a] - distance[b]);
        pq.offer(s - 1);
 
        while (!pq.isEmpty()) {
            int u = pq.poll();
            for (Edge edge : graph.get(u)) {
                int v = edge.to;
                int w = edge.weight;
                if (distance[u] + w < distance[v]) {
                    distance[v] = distance[u] + w;
                    pq.offer(v);
                }
            }
        }
 
        System.out.println(distance[t - 1]);
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值