描述
某通信网络中有N个网络结点,用1到N进行标识。网络通过一个有向无环图表示,其中图的边的值表示结点之间的消息传递时延现给定相连节点之间的时延列表times!=(u,v,w),其中u表示源结点,v表示目的结点,w表示u和v之间的消息传递时延请计算给定源结点到目的结点的最小传输时延,如果目的结点不可达,返回-1。
N的取值范围为[1,100];
时延列表times的长度不超过6000,且1<=u,v<=N,0<=W<=100。
输入描述
输入的第一行为两个正整数,分别表示网络结点的个数N,以及时延列表的长M,用空格分隔;接下来的M行为两个结点间的时延列表[uvW;输入的最后一行为两个正整数,分别表示源结点和目的结点,
输出描述
起点到终点得最小时延,不可达则返回-1。
用例
输入:
3 3
1 2 11
2 3 13
1 3 50
1 3
输出:
24
java实现
package com.des.data.test;
import java.util.*;
public class Dijkstra {
private static final int INF = Integer.MAX_VALUE / 2;
public static void main(String[] args) {
int[][] times = {
{1, 2, 11},
{2, 3, 13},
{1, 3, 50}
};
System.out.println(shortestPath(3, times, 1, 3));
}
/**
*
* @param N number of node
* @param times delay List
* @param src dtart broadcasting node
* @param dst end broadcasted node
* @return
*/
public static int shortestPath(int N, int[][] times, int src, int dst) {
HashMap<Integer, HashMap<Integer, Integer>> graph = new HashMap<>();
for (int[] edge : times) {
int u = edge[0];
int v = edge[1];
int w = edge[2];
graph.computeIfAbsent(u, k -> new HashMap<>()).put(v, w);
}
// a[1] reach the node a[0] cost time, it will be more than 1, but the fast is on the pq top
PriorityQueue<int[]> pq = new PriorityQueue<>(Comparator.comparingInt(a -> a[1]));
pq.offer(new int[]{src, 0});
HashMap<Integer, Integer> dist = new HashMap<>();
dist.put(src, 0);
while (!pq.isEmpty()) {
int[] cur = pq.poll();//get header element and delete it
int u = cur[0];
int d = cur[1];
if (u == dst) return d; //It is reachable
if (d > dist.getOrDefault(u, INF)) {
continue;
}
if (!graph.containsKey(u)) {
continue;
}
for (int v : graph.get(u).keySet()) {
int w = graph.get(u).get(v);
if (dist.getOrDefault(v, INF) > d + w) {
dist.put(v, d + w);
pq.offer(new int[]{v, d + w});
}
}
}
return -1;
}
}