1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| package org.stone.study.algo.ex202411;
import java.util.*;
public class VirusInfectTime {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); int m = Integer.parseInt(scanner.nextLine());
int[][] conn = new int[m][3]; for(int i = 0; i < m; i++) { conn[i] = Arrays.stream(scanner.nextLine().split(" ")).mapToInt(Integer::parseInt).toArray(); } int src = scanner.nextInt(); int ans = getMinInfectTime(n, m, conn, src); System.out.println(ans); }
private static int getMinInfectTime(int n, int m, int[][] conn, int src) { Map<Integer, List<int[]>> graph = new HashMap<>(); for(int[] edge : conn) { int u = edge[0]; int v = edge[1]; int w = edge[2]; graph.computeIfAbsent(u, k -> new ArrayList<>()).add(new int[]{v, w}); }
PriorityQueue<int[]> queue = new PriorityQueue<>(Comparator.comparingInt(e -> e[0])); int[] dist = new int[n + 1]; Arrays.fill(dist, Integer.MAX_VALUE); queue.add(new int[]{0, src}); dist[src] = 0; while(!queue.isEmpty()) { int[] cur = queue.poll(); int curTime = cur[0]; int curNode = cur[1];
if(curTime > dist[curNode]) { continue; } for(int[] next : graph.getOrDefault(curNode, Collections.emptyList())) { int nextNode = next[0]; int nextTime = next[1]; if(curTime + nextTime < dist[nextNode]) { dist[nextNode] = curTime + nextTime; queue.add(new int[]{dist[nextNode], nextNode}); } }
}
int ans = 0; for(int i = 1; i <= n; i++) { if(dist[i] == Integer.MAX_VALUE) { return -1; } ans = Math.max(ans, dist[i]); }
return ans; }
}
|