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
| class Solution { public int[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) { List<int[]>[] g = new ArrayList[n]; Arrays.setAll(g, e -> new ArrayList<>()); for (int i = 0; i < edges.length; ++i) { int x = edges[i][0], y = edges[i][1]; g[x].add(new int[]{y, i}); g[y].add(new int[]{x, i}); } int[][] distance = new int[n][2]; for (int i = 0; i < n; i++) { if (i != source) { distance[i][0] = distance[i][1] = Integer.MAX_VALUE; } }
dijkstra(g, edges, destination, distance, 0, 0); int delta = target - distance[destination][0]; if (delta < 0) return new int[][]{};
dijkstra(g, edges, destination, distance, delta, 1); if (distance[destination][1] < target) return new int[][]{};
for (int[] e : edges) { if (e[2] == -1) e[2] = 1; } return edges; }
private void dijkstra(List<int[]> g[], int[][] edges, int destination, int[][] distance, int delta, int k) { int n = g.length; boolean[] visited = new boolean[n]; for (; ; ) { int x = -1; for (int i = 0; i < n; ++i) { if (!visited[i] && (x < 0 || distance[i][k] < distance[x][k])) x = i; } if (x == destination) return; visited[x] = true; for (int[] e : g[x]) { int y = e[0], eid = e[1]; int wt = edges[eid][2]; if (wt == -1) wt = 1; if (k == 1 && edges[eid][2] == -1) { int w = delta + distance[y][0] - distance[x][1]; if (w > wt) edges[eid][2] = wt = w; } distance[y][k] = Math.min(distance[y][k], distance[x][k] + wt); } } } }
|