LeetCode刷题16-最小传输时延

package com.example.demo.leetcode.case202208;

import java.util.*;

/**
 * 功能描述
 *
 * @author ASUS
 * @version 1.0
 * @Date 2022/8/7
 */
public class Main2022080703 {
    /*
    【编程题目 | 200分】最小传输时延 [ 200 / 中等 ]
     题目描述
     某通信网络中有N个网络结点,用1到N进行标识。网络通过一个有向无环图表示,其中图的边的值表示结点之间的消息传递时延。
     现给定相连节点之间的时延列表times[i]={u,v,w},其中u表示源结点,v表示目的结点,w表示u和v之间的消息传递时延。
     请计算给定源结点到目的结点的最小传输时延,如果目的结点不可达,返回-1。
     注:

     N的取值范围为[1,100];
     时延列表times的长度不超过6000,且 1 <= u,v <= N,0 <= w <= 100;
     输入描述
     输入的第一行为两个正整数,分别表示网络结点的个数N,以及时延列表的长度M,用空格分隔;
     接下来的M行为两个结点间的时延列表[u v w];
     输入的最后一行为两个正整数,分别表示源结点和目的结点。
     输出描述
     起点到终点得最小时延,不可达则返回-1

     示例
     输入
     3 3
     1 2 11
     2 3 13
     1 3 50
     1 3

     输出
     24
     思路分析
     典型的有向图的单源最短路径,可以使用Dijkstra算法计算起点到终点的最短时延。
     使用优先队列实现算法中每次取最短路径。
     提供两种连接关系的表示方法,包括邻接表和邻接矩阵。
     注:邻接矩阵表示的时候,不要赋值Integer.MAX_VALUE,会溢出,+1,变为负数
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        int M = in.nextInt();
        int[][] times = new int[M][3];
        for (int i = 0; i < M; i++) {
            times[i][0] = in.nextInt();
            times[i][1] = in.nextInt();
            times[i][2] = in.nextInt();
        }
        int start = in.nextInt();
        int end = in.nextInt();

        // Dijkstra算法,邻接矩阵
        int maxValue = 6001;  // 不能用Integer.MAX_VALUE,最大值会出现溢出
        int[][] graph = new int[N + 1][N + 1];  // 邻接矩阵
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= N; j++) {
                graph[i][j] = (i == j ? 0 : maxValue);
            }
        }
        // 将时序存放到对应的坐标位置上
        for (int i = 0; i < times.length; i++) {
            int v = times[i][0]; // 源节点
            int w = times[i][1]; // 目标节点
            int weight = times[i][2]; // 长度
            graph[v][w] = weight;
        }
        int[] dist = new int[N + 1];
        PriorityQueue<Integer> queue = new PriorityQueue<>();
        Arrays.fill(dist, maxValue);
        dist[start] = 0;
        queue.add(start);
        while (!queue.isEmpty()) {
            int node = queue.poll();
            for (int next = 1; next <= N; next++) {
                if (dist[node] + graph[node][next] < dist[next]) {
                    dist[next] = dist[node] + graph[node][next];
                    queue.add(next);
                }
            }
        }
        if (dist[end] == maxValue) {
            System.out.println(-1);
        } else {
            System.out.println(dist[end]);
        }
    }

}

 

posted @ 2022-08-07 12:25  chch213  阅读(456)  评论(1编辑  收藏  举报