|
| 1 | +function modifiedGraphEdges( |
| 2 | + n: number, |
| 3 | + edges: number[][], |
| 4 | + source: number, |
| 5 | + destination: number, |
| 6 | + target: number, |
| 7 | +): number[][] { |
| 8 | + let fromDestination: number[] = []; |
| 9 | + const adjMatrix: number[][] = new Array(n).fill(0).map(() => |
| 10 | + new Array(n).fill(-1) |
| 11 | + ); |
| 12 | + // 邻接矩阵中存储边的下标 |
| 13 | + for (let i = 0; i < edges.length; ++i) { |
| 14 | + const u = edges[i][0], v = edges[i][1]; |
| 15 | + adjMatrix[u][v] = adjMatrix[v][u] = i; |
| 16 | + } |
| 17 | + fromDestination = dijkstra( |
| 18 | + 0, |
| 19 | + destination, |
| 20 | + edges, |
| 21 | + adjMatrix, |
| 22 | + target, |
| 23 | + fromDestination, |
| 24 | + ); |
| 25 | + if (fromDestination[source] > target) { |
| 26 | + return []; |
| 27 | + } |
| 28 | + const fromSource = dijkstra( |
| 29 | + 1, |
| 30 | + source, |
| 31 | + edges, |
| 32 | + adjMatrix, |
| 33 | + target, |
| 34 | + fromDestination, |
| 35 | + ); |
| 36 | + if (fromSource[destination] !== target) { |
| 37 | + return []; |
| 38 | + } |
| 39 | + return edges; |
| 40 | +} |
| 41 | + |
| 42 | +function dijkstra( |
| 43 | + op: number, |
| 44 | + source: number, |
| 45 | + edges: number[][], |
| 46 | + adjMatrix: number[][], |
| 47 | + target: number, |
| 48 | + fromDestination: number[], |
| 49 | +) { |
| 50 | + // 朴素的 dijkstra 算法 |
| 51 | + // adjMatrix 是一个邻接矩阵 |
| 52 | + const n = adjMatrix.length; |
| 53 | + const dist = new Array(n).fill(Number.MAX_SAFE_INTEGER); |
| 54 | + const used = new Array(n).fill(false); |
| 55 | + dist[source] = 0; |
| 56 | + |
| 57 | + for (let round = 0; round < n - 1; ++round) { |
| 58 | + let u = -1; |
| 59 | + for (let i = 0; i < n; ++i) { |
| 60 | + if (!used[i] && (u === -1 || dist[i] < dist[u])) { |
| 61 | + u = i; |
| 62 | + } |
| 63 | + } |
| 64 | + used[u] = true; |
| 65 | + for (let v = 0; v < n; ++v) { |
| 66 | + if (!used[v] && adjMatrix[u][v] !== -1) { |
| 67 | + if (edges[adjMatrix[u][v]][2] !== -1) { |
| 68 | + dist[v] = Math.min( |
| 69 | + dist[v], |
| 70 | + dist[u] + edges[adjMatrix[u][v]][2], |
| 71 | + ); |
| 72 | + } else { |
| 73 | + if (op == 0) { |
| 74 | + dist[v] = Math.min(dist[v], dist[u] + 1); |
| 75 | + } else { |
| 76 | + const modify = target - dist[u] - fromDestination[v]; |
| 77 | + if (modify > 0) { |
| 78 | + dist[v] = Math.min(dist[v], dist[u] + modify); |
| 79 | + edges[adjMatrix[u][v]][2] = modify; |
| 80 | + } else { |
| 81 | + edges[adjMatrix[u][v]][2] = target; |
| 82 | + } |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return dist; |
| 90 | +} |
| 91 | +export default modifiedGraphEdges; |
0 commit comments