有一个分布式服务集群,集群内含有 N 个服务节点,分别标记为 1 到 N。
给予一个列表 times,表示消息从两个节点间有向传递需要的时间。 times[i] = (s, d, t),其中 s 表示发出消息的源节点,d 表示接收到消息的目标节点, t 表示信息有向传递的时间。
现在 K 节点发送了一个信号,请问至少需要多少秒才能使所有的服务节点都收到该消息?如果消息不能传递给集群内全部节点,则返回-1。
第一行:列表 times。分布式服务集群的图,图的结构为二维数组。例如: [[2,1,1],[2,3,1],[3,4,1]] ,表示集群4个节点,2到1的时间为1,2到3的时间为1,3到4的时间为1;
第二行:N值
第三行:K值
范围约束:
1. N 的范围在 [1, 100] 之间。
2. K 的范围在 [1, N] 之间。
3. times 的长度在 [1, 6000] 之间。
4. 所有的边 times[i] = (s, d, t) 都有 1 <= s, d <= N 且 1 <= t <= 100。
至少需要多少秒才能使所有的服务节点都收到该消息?如果消息不能传递给集群内全部节点,则返回-1
[[2,1,1],[2,3,1],[3,4,1]] 4 2
2
图可能存在重边或自环
import java.util.*; // Dijkstra:单源最短路径 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String line = in.next(); int n = in.nextInt(), k = in.nextInt(); List<List<int[]>> g = new ArrayList<>(); // 邻接表 for (int i = 0; i <= n; i++) { g.add(new ArrayList<>()); } line = line.substring(2, line.length() - 2); // 处理输入 String[] sp = line.split("\\],\\["); // 去掉首尾[[ ]], 中间可以用],[分割 for (String str : sp) { String[] spp = str.split(","); int s = Integer.parseInt(spp[0]); int d = Integer.parseInt(spp[1]); int t = Integer.parseInt(spp[2]); g.get(s).add(new int[] {d, t}); // 有向图 // g.get(d).add(new int[] {s, t}); } int[] dist = new int[n + 1]; // k点到其他点的距离 int INF = Integer.MAX_VALUE >> 1; Arrays.fill(dist, INF); dist[k] = 0; PriorityQueue<int[]> queue = new PriorityQueue<>((a, b)->a[1] - b[1]); queue.offer(new int[] {k, 0}); while (!queue.isEmpty()) { int[] a = queue.poll(); int s = a[0], dis = a[1]; if (dis > dist[s]) continue; for (int[] b : g.get(s)) { int d = b[0], t = b[1]; int newDis = dis + t; if (newDis < dist[d]) { dist[d] = newDis; b[1] = newDis; queue.offer(b); } } } int max = -1; for (int i = 1; i <= n; i++) { // k到其他点的最长距离 if (dist[i] == INF) { max = -1; break; } max = Math.max(dist[i], max); } System.out.println(max); } }