{"id":"cheapest-signed-path","title":"Cheapest Signed Path","difficulty":"medium","patterns":["bellman-ford"],"primaryConcept":"graph-shortest-path-negative","concepts":["graph-shortest-path-negative"],"problemForm":"core","companies":["Amazon","Google","Meta","Microsoft"],"category":"trees-graphs","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"graph-edges","primaryParam":"edges","sizeMetric":"nodes-plus-edges","secondaryParams":{"n":{"strategy":"scale-with-primary"},"src":{"strategy":"fixed","value":0},"dst":{"strategy":"scale-with-primary"}},"constraints":["weighted","signed-weights"]},"description":"You are given a directed weighted graph with `n` nodes, an edge list `edges`, a source `src`, and a destination `dst`.\n\nEach edge is `[u, v, w]`, meaning travel from `u` to `v` costs `w`. Edge weights may be negative, but there is no reachable negative cycle. Return the cheapest cost from `src` to `dst`. If `dst` is unreachable, return `1000000000`.","examples":[{"input":"n = 5, edges = [[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]], src = 0, dst = 4","output":"4","explanation":"The cheapest route is 0 -> 1 -> 2 -> 3 -> 4 with cost 4 + (-3) + 2 + 1 = 4."},{"input":"n = 4, edges = [[0,1,2],[1,2,3]], src = 0, dst = 3","output":"1000000000","explanation":"Node 3 is unreachable from node 0."}],"constraints":[{"id":"1-n-500","text":"1 <= n <= 500","check":{"kind":"valueRange","target":"n","selector":"value","min":1,"max":500}},{"id":"0-len-edges-5000","text":"0 <= len(edges) <= 5000","check":{"kind":"sizeRange","target":"edges","measure":"arrayLength","min":0,"max":5000}},{"id":"edges-i-length-3","text":"len(edges[i]) == 3","check":{"kind":"shape","target":"edges","shape":"tupleArray","tupleLength":3}},{"id":"0-edges-i-0-edges-i-1-n","text":"0 <= edges[i][0], edges[i][1] < n","check":[{"kind":"valueRange","target":"edges","selector":"tupleItemsAtIndex","index":0,"min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"edges","selector":"tupleItemsAtIndex","index":1,"min":0,"max":{"valueOfInput":"n","offset":-1}}]},{"id":"10-5-edges-i-2-10-5","text":"-10^5 <= edges[i][2] <= 10^5","check":{"kind":"valueRange","target":"edges","selector":"tupleItemsAtIndex","index":2,"min":-100000,"max":100000}},{"id":"0-src-dst-n","text":"0 <= src, dst < n","check":[{"kind":"valueRange","target":"src","selector":"value","min":0,"max":{"valueOfInput":"n","offset":-1}},{"kind":"valueRange","target":"dst","selector":"value","min":0,"max":{"valueOfInput":"n","offset":-1}}]},{"id":"no-negative-weight-cycle-is-reachable-from-src","text":"No negative-weight cycle is reachable from src"},{"id":"every-finite-shortest-path-cost-fits-in-a-32-bit-signed-integer","text":"Every finite shortest path cost fits in a 32-bit signed integer"}],"starterCode":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        # Your code here\n        pass","functionName":"cheapestSignedPath","testCases":[{"id":"1","input":{"n":5,"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]],"src":0,"dst":4},"expected":4,"description":"Negative edge improves the path."},{"id":"2","input":{"n":4,"edges":[[0,1,2],[1,2,3]],"src":0,"dst":3},"expected":1000000000,"description":"Destination is unreachable."},{"id":"3","input":{"n":4,"edges":[[0,1,1],[0,2,10],[1,2,-4],[2,3,2]],"src":0,"dst":3},"expected":-1,"description":"A valid reachable path can have negative total cost."},{"id":"4","input":{"n":3,"edges":[[0,1,5]],"src":2,"dst":2},"expected":0,"description":"Source equals destination."},{"id":"5","input":{"n":4,"edges":[[0,1,5],[1,2,5],[0,2,20],[2,3,-2],[1,3,10]],"src":0,"dst":3},"expected":8,"description":"Best path needs multiple relaxation passes."},{"id":"6","input":{"n":3,"edges":[[1,2,-5]],"src":0,"dst":2},"expected":1000000000,"description":"A negative edge in another component is irrelevant."},{"id":"h1","input":{"n":4,"edges":[[0,1,2],[1,3,2],[0,2,10],[2,3,-5]],"src":0,"dst":3},"expected":4,"description":"A direct positive route beats a longer route that uses a negative edge."},{"id":"h2","input":{"n":3,"edges":[],"src":1,"dst":1},"expected":0,"description":"Source and destination are the same vertex."},{"id":"h3","input":{"n":5,"edges":[[0,1,4],[0,2,10],[1,3,3],[2,3,-5],[3,4,1]],"src":0,"dst":4},"expected":6,"description":"A negative edge improves the best complete path."},{"id":"h4","input":{"n":4,"edges":[[0,1,2],[1,0,-1],[2,3,-2]],"src":0,"dst":3},"expected":1000000000,"description":"A separate component does not help reach the destination."},{"id":"h5","input":{"n":4,"edges":[[0,1,5],[0,2,2],[2,1,-4],[1,3,3],[2,3,10]],"src":0,"dst":3},"expected":1,"description":"A negative edge between reachable nodes improves the best route without forming a cycle."},{"id":"h6","input":{"n":5,"edges":[[0,1,2],[1,2,2],[0,2,10],[2,3,-1],[3,4,2],[1,4,10]],"src":0,"dst":4},"expected":5,"description":"The shortest route combines positive and negative edges over several hops."},{"id":"path-edges-listed-in-reverse","input":{"n":3,"edges":[[1,2,2],[0,1,7]],"src":0,"dst":2},"expected":9,"description":"The path 0 -> 1 -> 2 lists its edges in reverse order, so one pass over the edge list in order cannot reach node 2."}],"hints":[{"level":1,"content":"Negative edges rule out Dijkstra's greedy finalization."},{"level":2,"content":"Relax every edge repeatedly so paths with more edges can improve later nodes."},{"level":3,"content":"After at most n - 1 passes, every shortest simple path has had enough edge relaxations."}],"guidedFlow":{"progressRevision":"cheapest-signed-path-2026-07-19-greedy-premise-and-simple-path-bound","version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"dijkstra","name":"Greedy shortest path","summary":"Use a priority queue and finalize the nearest unvisited node.","decisionReason":"A negative edge can make a node cheaper after the priority queue has already finalized it, so the greedy nearest-node rule is not valid for these weights. The no-negative-cycle guarantee is enough for repeated relaxation instead.","complexity":{"time":"O(e log n)","space":"O(n + e)"},"tradeoffs":["Runs in O(e log n) time and uses O(n + e) space."],"isOptimal":false},{"id":"bellman-ford","name":"Repeated edge relaxation","summary":"Initialize distances, relax all edges for up to n - 1 passes, and return the destination distance.","decisionReason":"After pass i, dist[v] is the cheapest cost to v using at most i edges. Relaxing every edge for n - 1 passes covers every simple src-to-dst path, and the destination entry gives the answer or the unreachable sentinel.","complexity":{"time":"O(n * e)","space":"O(n)"},"tradeoffs":["Runs in O(n * e) time and uses O(n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"init-dist","title":"Initialize distances","description":"Set all distances to INF and seed the source distance with zero.","commonMistakes":["Initializing every node to zero","Forgetting to seed the source"],"hint":"Only the source is known at cost zero before relaxation starts.","semanticSpec":{"intent":"Initialize weighted shortest-path distance state.","doneWhen":"The distance array is filled with a sentinel and `dist[src]` is set to zero.","shouldFailWhen":"This step should fail if there is no distance state or if the source is not seeded.","roles":["distance array","source node","infinity sentinel"],"mustProve":["The code initializes weighted distance state.","The source node has distance zero."],"mustNotAccept":["Starting every node as reachable.","Using edge weights as initial distances."],"equivalentVariants":["Use a large integer sentinel for unreachable distances."],"proofSnippets":[{"id":"py-cheapest-signed-path-init-dist","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        return -1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"init-dist","readMode":"graph-value-query-v1"}]}},{"id":"compute-candidate","title":"Compute edge candidates","description":"For each reachable edge source, combine its distance with the edge weight before writing an update.","commonMistakes":["Using the destination distance as the candidate base","Ignoring the edge weight when comparing distances"],"hint":"The candidate distance is dist[u] + w for edge u -> v.","semanticSpec":{"intent":"Compute weighted Bellman-Ford candidates from edge entries.","doneWhen":"The code scans weighted edges inside the pass loop and compares a source-distance-plus-weight candidate against the destination distance.","shouldFailWhen":"This step should fail if edges are scanned without a weighted candidate comparison.","roles":["edge scan","source distance","edge weight","candidate distance"],"mustProve":["The code binds source, destination, and weight from each edge.","A candidate distance combines the source distance with the edge weight."],"mustNotAccept":["A loop over edges that ignores the weight.","A candidate based on the destination distance."],"equivalentVariants":["Store the candidate in a local variable before comparing.","Compute the candidate inline inside the comparison."],"proofSnippets":[{"id":"py-cheapest-signed-path-compute-candidate","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        for _ in range(n - 1):\n            for u, v, w in edges:\n                if dist[u] == INF:\n                    continue\n                cand = dist[u] + w\n                if cand < dist[v]:\n                    pass\n        return -1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"computes_weighted_edge_relaxation_candidate","scope":"relax-candidate","readMode":"graph-value-query-v1"}]}},{"id":"relax-edges","title":"Relax all edges repeatedly","description":"Run up to n - 1 passes over all edges and update better destination distances.","commonMistakes":["Relaxing each edge only once","Using the destination distance before checking source reachability"],"hint":"A shortest simple path can use at most n - 1 edges.","semanticSpec":{"intent":"Apply Bellman-Ford edge relaxation over repeated full edge scans.","doneWhen":"The code scans all weighted edges inside a pass loop and writes smaller candidate distances.","shouldFailWhen":"This step should fail if edges are not repeatedly relaxed.","roles":["pass loop","edge scan","candidate distance","distance update"],"mustProve":["The code repeatedly scans weighted edges.","The code updates a destination distance when a smaller candidate is found."],"mustNotAccept":["Only checking direct edges from the source.","Updating distances without source reachability."],"equivalentVariants":["Use an early-exit flag when a pass makes no updates."],"proofSnippets":[{"id":"py-cheapest-signed-path-relax-edges","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        for _ in range(n - 1):\n            for u, v, w in edges:\n                if dist[u] == INF:\n                    continue\n                cand = dist[u] + w\n                if cand < dist[v]:\n                    dist[v] = cand\n        return -1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"repeats_weighted_edge_relaxation","scope":"run-bf","readMode":"graph-value-query-v1"}]}},{"id":"return-result","title":"Return destination cost","description":"Return the finalized destination distance or the unreachable sentinel.","commonMistakes":["Returning the whole distance array","Treating negative finite costs as unreachable"],"hint":"Only INF means unreachable; a negative distance can be a valid cheapest cost.","semanticSpec":{"intent":"Return the relaxed scalar metric for the destination.","doneWhen":"The code returns the destination distance if finite and the unreachable sentinel otherwise.","shouldFailWhen":"This step should fail if the method returns all distances or a stale candidate.","roles":["destination node","finite distance","unreachable sentinel"],"mustProve":["The code reads the relaxed destination distance.","The code distinguishes finite distance from the unreachable sentinel."],"mustNotAccept":["Returning zero for unreachable destinations.","Returning the edge count instead of cost."],"equivalentVariants":["Use `1000000000` as the unreachable output sentinel."],"proofSnippets":[{"id":"py-cheapest-signed-path-return-result","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        for _ in range(n - 1):\n            for u, v, w in edges:\n                if dist[u] == INF:\n                    continue\n                cand = dist[u] + w\n                if cand < dist[v]:\n                    dist[v] = cand\n        OUT_INF = 1000000000\n        if dist[dst] == INF:\n            return OUT_INF\n        return int(dist[dst])"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_relaxed_metric_result","scope":"return-result","readMode":"graph-value-query-v1"}]}}],"slides":[{"id":"opener","kind":"info","chapter":"Understand","eyebrow":"Read the problem","title":"Cheapest cost from one node to another, minus signs allowed","workspacePanel":"problem","body":["You get `n` nodes labeled `0..n-1`, a list of directed edges each written `[u, v, w]` (a one-way arrow from `u` to `v` costing `w`), a source `src`, and a destination `dst`. Return the cheapest total cost to get from `src` to `dst`. Weights can be negative, but no negative cycle is reachable from `src`. If no path reaches `dst`, return the sentinel 1000000000.","Enumerating every simple path would find the cheapest cost, but the number of paths grows exponentially. Negative edges also mean a route that looks more expensive early can become the cheapest after later edges."]},{"id":"greedy-premise-probe","kind":"case-probe","chapter":"The greedy way","eyebrow":"Try to avoid listing paths","title":"If every future edge adds zero or more, can a later route beat cost 1?","summary":"From node 0, the best known costs are 1 to node 1 and 4 to node 2. Any route discovered through node 2 must start at 4, and every remaining edge is non-negative.","workspacePanel":"visualizer","options":[{"id":"cannot-beat","label":"No; starting from 4 and adding non-negative costs can never get below 1","rationale":"The smallest tentative cost is safe when every later step can only keep or increase a route's total. That makes it reasonable to settle node 1 and stop reconsidering it.","isCorrect":true},{"id":"may-beat","label":"Yes; a longer route can always become cheaper regardless of its edge weights","rationale":"More edges alone do not make a route cheaper. With all remaining weights non-negative, a route already starting at 4 cannot undercut 1.","isCorrect":false},{"id":"must-enumerate","label":"There is no conclusion until every path has been enumerated","rationale":"The non-negative weights provide the missing conclusion: once 1 is the smallest frontier cost, no unsettled route can later fall below it.","isCorrect":false}],"answer":"No. When every future edge is non-negative, the smallest tentative cost cannot be undercut later. That is the reason a nearest-first greedy method can settle a node; now test that promise against the signed edges this problem actually allows.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"nonnegative-frontier","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,5]],"current":0,"highlighted":[1,2]},"arrays":[{"name":"best known cost","values":[0,1,4],"current":1}]}}]}},{"id":"greedy-contrast","kind":"code-trace","source":"greedy","chapter":"The greedy way","eyebrow":"The tempting shortcut","title":"Settle the nearest node, then never look back","summary":"Enumerating every path is too slow, so the tempting shortcut is the greedy frontier: repeatedly take the closest unsettled node, lock its cost as final, and relax its edges. It skips the exponential path scan and is correct when every weight is non-negative. Watch it commit to node 1 before the negative edge 2->1 ever fires.","workspacePanel":"trace","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def cheapest(n: int, edges: list[list[int]], src: int, dst: int) -> int:\n    INF = 1000000000000000000\n    dist = [INF] * n\n    dist[src] = 0\n    settled = [False] * n\n    for _ in range(n):\n        u = -1\n        for x in range(n):\n            if not settled[x] and (u == -1 or dist[x] < dist[u]):\n                u = x\n        settled[u] = True\n        for a, b, w in edges:\n            if a == u and not settled[b] and dist[u] + w < dist[b]:\n                dist[b] = dist[u] + w\n    return dist[dst]","steps":[{"id":"settle-0","title":"Settle node 0 and relax its edges","codeLine":11,"summary":"Node 0 is closest at cost 0, so it settles. Its edges set dist[1] = 1 and dist[2] = 4.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"current":0,"highlighted":[1,2],"activeEdges":[[0,1],[0,2]]},"arrays":[{"name":"dist","values":[0,1,4],"current":0}]}},{"id":"settle-1","title":"Node 1 is nearest, so its cost 1 is locked","codeLine":11,"summary":"Among unsettled nodes, node 1 at cost 1 is closest, so greedy settles it and treats dist[1] = 1 as final. Node 1 has no outgoing edges to relax.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"current":1,"highlighted":[]},"arrays":[{"name":"dist","values":[0,1,4],"current":1}]}},{"id":"settle-2","title":"Node 2 settles and edge 2->1 is considered","codeLine":13,"summary":"Node 2 settles at cost 4 and its outgoing edge 2->1 becomes active. After this code step, dist[1] is still 1. The next page asks why this candidate failed to change the table.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"current":2,"highlighted":[1],"activeEdges":[[2,1]]},"arrays":[{"name":"dist","values":[0,1,4],"current":1}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const INF = unsupportedIntegerLiteral(\"1000000000000000000\");\nconst dist = Array.from({ length: n }, () => INF);\ndist[src] = 0;\nconst settled = Array(n).fill(false);\nfor (let i = 0; i < n; i++) {\n    let u = -1;\n    for (let x = 0; x < n; x++) {\n        if (!settled[x] && (u === -1 || dist[x] < dist[u])) {\n            u = x;\n        }\n    }\n    settled[u] = true;\n    for (const [a, b, w] of edges) {\n        if (a === u && !settled[b] && (dist[u] + w) < dist[b]) {\n            dist[b] = (dist[u] + w);\n        }\n    }\n}\nreturn dist[dst];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":12,"12":13,"13":14,"14":15,"15":19},"statementBundles":{"10":{"startLine":9,"endLine":11},"14":{"startLine":15,"endLine":18}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const INF = unsupportedIntegerLiteral(\"1000000000000000000\");\nconst dist = Array.from({ length: n }, () => INF);\ndist[src] = 0;\nconst settled = Array(n).fill(false);\nfor (let i = 0; i < n; i++) {\n    let u = -1;\n    for (let x = 0; x < n; x++) {\n        if (!settled[x] && (u === -1 || dist[x] < dist[u])) {\n            u = x;\n        }\n    }\n    settled[u] = true;\n    for (const [a, b, w] of edges) {\n        if (a === u && !settled[b] && (dist[u] + w) < dist[b]) {\n            dist[b] = (dist[u] + w);\n        }\n    }\n}\nreturn dist[dst];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":12,"12":13,"13":14,"14":15,"15":19},"statementBundles":{"10":{"startLine":9,"endLine":11},"14":{"startLine":15,"endLine":18}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"long INF = 1000000000000000000L;\nList<long> dist = Enumerable.Range(0, n).Select(_ => INF).ToList();\ndist[src] = 0;\nList<bool> settled = Enumerable.Repeat<bool>(false, n).ToList();\nfor (int i = 0; i < n; i++) {\n    int u = -1;\n    for (int x = 0; x < n; x++) {\n        if (!settled[x] && (u == -1 || dist[x] < dist[u])) {\n            u = x;\n        }\n    }\n    settled[u] = true;\n    foreach (var item in edges) {\n        int a = item[0];\n        int b = item[1];\n        int w = item[2];\n        if (a == u && !settled[b] && dist[u] + w < dist[b]) {\n            dist[b] = dist[u] + w;\n        }\n    }\n}\nreturn checked((int)dist[dst]);","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":12,"12":13,"13":17,"14":18,"15":22},"statementBundles":{"10":{"startLine":9,"endLine":11},"12":{"startLine":13,"endLine":16},"14":{"startLine":18,"endLine":21}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"long long INF = 1000000000000000000LL;\nvector<long long> dist = vector<long long>(n, INF);\ndist[src] = 0;\nvector<bool> settled = vector<bool>(n, false);\nfor (int i = 0; i < n; i++) {\n    int u = -1;\n    for (int x = 0; x < n; x++) {\n        if ((!settled[x] && (u == -1 || dist[x] < dist[u]))) {\n            u = x;\n        }\n    }\n    settled[u] = true;\n    for (vector<int> item : edges) {\n        int a = item[0];\n        int b = item[1];\n        int w = item[2];\n        if (((a == u && !settled[b]) && (dist[u] + w) < dist[b])) {\n            dist[b] = static_cast<long long>((dist[u] + w));\n        }\n    }\n}\nreturn dist[dst];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":8,"10":9,"11":12,"12":13,"13":17,"14":18,"15":22},"statementBundles":{"10":{"startLine":9,"endLine":11},"12":{"startLine":13,"endLine":16},"14":{"startLine":18,"endLine":21}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"long INF = 1000000000000000000L;\nList<Long> dist = new ArrayList<>();\nfor (int index = 0; index < n; index++) {\n    dist.add(((long)(INF)));\n}\ndist.set(src, 0L);\nList<Boolean> settled = new ArrayList<>();\nfor (int index = 0; index < n; index++) {\n    settled.add(false);\n}\nfor (int i = 0; i < n; i++) {\n    int u = -1;\n    for (int x = 0; x < n; x++) {\n        if ((!settled.get(x) && (u == -1 || dist.get(x) < dist.get(u)))) {\n            u = x;\n        }\n    }\n    settled.set(u, true);\n    for (List<Integer> edge : edges) {\n        int a = edge.get(0);\n        int b = edge.get(1);\n        int w = edge.get(2);\n        if (((a == u && !settled.get(b)) && (dist.get(u) + w) < dist.get(b))) {\n            dist.set(b, ((long)((dist.get(u) + w))));\n        }\n    }\n}\nreturn Math.toIntExact(dist.get(dst));","lineMap":{"2":1,"3":2,"4":6,"5":7,"6":11,"7":12,"8":13,"9":14,"10":15,"11":18,"12":19,"13":23,"14":24,"15":28},"statementBundles":{"3":{"startLine":2,"endLine":5},"5":{"startLine":7,"endLine":10},"10":{"startLine":15,"endLine":17},"12":{"startLine":19,"endLine":22},"14":{"startLine":24,"endLine":27}}}}}},{"id":"greedy-cost","kind":"case-probe","chapter":"The greedy way","eyebrow":"Why it hurts","title":"Why did greedy report dist[1] = 1 instead of -1?","summary":"Edge 2->1 carries -5, and node 2 settles at cost 4, so 4 + (-5) = -1 beats the 1 greedy already wrote for node 1.","workspacePanel":"visualizer","options":[{"id":"locked","label":"Node 1 was locked the moment it was settled, before the negative edge into it fired","rationale":"Greedy settles the nearest node first and never reopens it. Node 1 settled at 1 while node 2 was still unsettled, so when 2->1 later offered -1, the relaxation into a settled node was skipped. A negative edge can always undercut a cost after it was committed, which is the assumption greedy depends on and this graph breaks.","isCorrect":true},{"id":"wrong-order","label":"The edges were listed in the wrong order; sorting them fixes it","rationale":"No edge order saves greedy here. The problem is settling node 1 before node 2 is explored at all; reordering the edge list does not change which node is closest at each step.","isCorrect":false},{"id":"missing-edge","label":"The graph is missing a direct 0->1 shortcut","rationale":"The direct edge 0->1 exists and gave dist[1] = 1. The cheaper route is the two-hop 0->2->1 at -1, which greedy refuses to apply because node 1 is already settled.","isCorrect":false}],"answer":"Node 1 was settled at cost 1 before node 2 was explored, and greedy never reopens a settled node. So when edge 2->1 offered -1 later, it was thrown away. With negative edges, a cheaper path can arrive after a node looks final, so nothing can be locked on first reach.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"greedy-cost-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"current":2,"highlighted":[1],"activeEdges":[[2,1]]},"arrays":[{"name":"dist","values":[0,1,4],"current":1}]}}]}},{"id":"insight","kind":"case-probe","chapter":"The fix","eyebrow":"Undo the bad commitment","title":"Edge 2->1 offers -1 after dist[1] was set to 1. What should the table do?","summary":"The edge calculation is valid: dist[2] + (-5) = 4 - 5 = -1. The only reason greedy rejected it was that node 1 had already been settled.","workspacePanel":"visualizer","options":[{"id":"reapply","label":"Replace dist[1] with -1 even though node 1 was handled earlier","rationale":"The table represents the cheapest route found so far and remains open to improvement. Any edge that offers a lower total must be allowed to update its destination.","isCorrect":true},{"id":"sort-first","label":"Keep dist[1] = 1 because changing an earlier result would break the traversal order","rationale":"That is the greedy commitment that produced the wrong answer. The later route is genuinely cheaper, so preserving 1 would make the table false.","isCorrect":false},{"id":"track-paths","label":"Store both 1 and -1 permanently because they came from different routes","rationale":"Future edges only need the cheapest known arrival. Keeping the larger 1 cannot produce a cheaper continuation than starting from -1, so one replaceable number is enough.","isCorrect":false}],"answer":"Replace dist[1] with -1. A distance entry is the cheapest arrival found so far, so any edge may lower it even after that node was handled earlier. The next question is how that late improvement reaches edges that were already checked.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"insight-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"current":2,"highlighted":[1],"activeEdges":[[2,1]]},"arrays":[{"name":"dist","values":[0,1,4],"current":1}]}}]}},{"id":"propagate-late-improvement-probe","kind":"case-probe","chapter":"The fix","eyebrow":"Carry the improvement forward","title":"dist[1] drops after edge 1->3 was already checked. How can the cheaper cost still reach node 3?","summary":"Earlier in the pass, edge 1->3 used dist[1] = 1 and wrote dist[3] = 3. Near the end, edge 2->1 lowers dist[1] to -1, so node 3 should eventually become 1 instead.","workspacePanel":"visualizer","options":[{"id":"scan-again","label":"Scan every edge again so 1->3 can use the newly lowered dist[1]","rationale":"The first pass exposed the late improvement; another full pass lets every outgoing edge see it. Repeating the same local relaxation carries cheaper costs one edge farther without choosing a permanent node order.","isCorrect":true},{"id":"negative-only","label":"Recheck only the negative edge 2->1","rationale":"That edge already produced -1. The missing update is on the positive edge 1->3, so negative edges alone cannot propagate the cheaper cost onward.","isCorrect":false},{"id":"keep-three","label":"Keep dist[3] = 3 because edge 1->3 already had its turn","rationale":"That would preserve another stale result. Once dist[1] improves, every edge leaving node 1 deserves a chance to use the new value.","isCorrect":false}],"answer":"Scan the full edge list again. The next pass revisits 1->3 after dist[1] has become -1, so it lowers dist[3] from 3 to 1. Repeated full-edge relaxation is not an arbitrary replacement for greedy; it is how late improvements propagate through later edges.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"late-improvement-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,1],[1,3,2],[0,2,4],[2,1,-5]],"current":1,"highlighted":[3],"activeEdges":[[1,3]]},"arrays":[{"name":"dist after the late update","values":[0,-1,4,3],"current":3}]}}]}},{"id":"simple-path-bound-probe","kind":"case-probe","chapter":"The fix","eyebrow":"Remove repeated work","title":"A cheapest route visits node 1 twice. Does the loop between those visits have to stay?","summary":"No reachable negative cycle exists. The segment from the first visit to node 1 until the route returns to node 1 is therefore a cycle whose total cost is zero or positive.","workspacePanel":"visualizer","options":[{"id":"remove-cycle","label":"Remove the cycle; the route stays equally cheap or becomes cheaper","rationale":"The cycle returns to the same node and costs at least zero. Cutting it out preserves the route's endpoints and cannot raise the total, so some cheapest route never repeats a node.","isCorrect":true},{"id":"keep-cycle","label":"Keep the cycle because negative edges may appear inside it","rationale":"Individual edges may be negative, but the whole cycle cannot be negative under the problem's promise. Only the cycle's total determines whether removing it hurts.","isCorrect":false},{"id":"duplicate-route","label":"Duplicate the cycle until every edge has been tried","rationale":"Repeating a zero-or-positive cycle cannot improve the route and creates unbounded extra work.","isCorrect":false}],"answer":"Remove it. Because a reachable cycle cannot have negative total cost, deleting the loop preserves or lowers the route's cost. Therefore at least one cheapest route is simple: it visits each node at most once.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-node-route","state":{"arrays":[{"name":"route","values":[0,1,2,1,3],"highlighted":[1,2,3]}],"values":{"cycle":"1 -> 2 -> 1","cycleCost":">= 0"}}}]}},{"id":"reframe","kind":"case-probe","chapter":"The fix","eyebrow":"Bound the work","title":"A simple route through n nodes can use at most how many edges?","summary":"The previous step showed that some cheapest route never repeats a node. Each full edge sweep can carry correct costs across one more edge of such a route.","workspacePanel":"visualizer","options":[{"id":"n-minus-1","label":"n-1 edges","rationale":"After sweep k, every cost reachable by a path of at most k edges is correct, because each sweep extends every settled path by one more edge. A shortest path that never repeats a node visits at most n nodes, so it spans at most n-1 edges. Therefore n-1 sweeps let every honest shortest path settle.","isCorrect":true},{"id":"one-sweep","label":"n edges","rationale":"A route with n edges visits n+1 node positions, so at least one of the n available nodes must repeat. The repeated cycle can be removed without making the route more expensive.","isCorrect":false},{"id":"until-negative","label":"There is no finite bound because edge weights may be negative","rationale":"Negative edges do not force repeated nodes. With reachable negative cycles excluded, a cheapest route can be simple and therefore has a finite n-1-edge bound.","isCorrect":false}],"answer":"At most n-1 edges. A simple route can visit each of the n nodes once, so it can cross at most n-1 links. Since sweep k carries correct costs across paths of up to k edges, n-1 sweeps are enough.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"reframe-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"highlighted":[0,2,1]},"arrays":[{"name":"simple route through three nodes","values":[0,2,1],"highlighted":[0,1,2]}]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The fix","eyebrow":"Pick the route","title":"Which approach survives negative edges?","summary":"Compare the greedy frontier with repeated full passes over the edge list.","workspacePanel":"visualizer","selection":{"contract":"approach-selection-v1","question":"Which approach survives negative edges?","decisionPrompt":"Pick the approach that still finds the true cheapest cost when an edge weight is negative.","approaches":[{"id":"dijkstra","name":"Greedy: settle the nearest node, never revisit","summary":"Repeatedly pick the closest unsettled node, lock its cost, and relax its outgoing edges.","decisionReason":"Locking the nearest node assumes no cheaper path can arrive later, but a negative edge into an already-settled node would have lowered it. Greedy reports the stale value and never reopens it.","complexity":{"time":"O((V+E) log V)","space":"O(V)"},"tradeoffs":["Fast, but only correct when every edge weight is non-negative."],"isOptimal":false},{"id":"bellman-ford","name":"Repeated relaxation","summary":"Keep one cheapest-cost number per node and sweep all edges n-1 times, letting any edge lower a cost as often as it can.","decisionReason":"A shortest path uses at most n-1 edges, so n-1 full sweeps let every negative shortcut take effect. Nothing is ever locked, so a late negative edge still improves the cost it should.","complexity":{"time":"O(V*E)","space":"O(V)"},"tradeoffs":["Scans all edges every round, but the work stays a flat O(V*E) regardless of weights."],"isOptimal":true}]},"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,1],[0,2,4],[2,1,-5]],"current":2,"highlighted":[1],"activeEdges":[[2,1]]},"arrays":[{"name":"dist","values":[0,-1,4]}]}}]}},{"id":"seed","kind":"case-probe","chapter":"The fix","eyebrow":"Seed the distances","title":"What should every starting cost be?","summary":"This problem grows costs out from one chosen source, src = 0, and asks only for the one node dst.","workspacePanel":"visualizer","options":[{"id":"src-only","label":"0 at src and the unreachable sentinel everywhere else","rationale":"Seeding only src at 0 means the relaxation grows outward from the source alone. Any node no path from src can reach keeps its sentinel, so if dst keeps its sentinel to the end, that is exactly the 1000000000 answer the problem wants for an unreachable destination.","isCorrect":true},{"id":"all-zero","label":"0 at every node","rationale":"Seeding every node at 0 invents free arrivals everywhere, so dst would report 0 even when no path from src reaches it, and costs would be measured from the wrong starts. All-zero seeding answers a different question.","isCorrect":false},{"id":"all-inf","label":"The sentinel at every node, including src","rationale":"If src also starts at the sentinel, no edge ever fires, because sentinel + w is not below sentinel. The source has to start finite to seed the very first relaxation; everything reachable flows out from it.","isCorrect":false}],"answer":"Seed dist[src] = 0 and every other node at the unreachable sentinel. The relaxations grow from the one source, and a destination the source cannot reach keeps its sentinel, which becomes the 1000000000 answer.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"seed-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]],"highlighted":[0]},"arrays":[{"name":"dist (src = 0 highlighted, costs not yet seeded)","values":["?","?","?","?","?"],"current":0}]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it run","title":"Seed src at 0, then sweep the edges","workspacePanel":"visualizer","body":["Run it on the opening graph: n = 5, src = 0, dst = 4, edges 0->1 (4), 0->2 (5), 1->2 (-3), 2->3 (2), 3->4 (1). dist starts [0, INF, INF, INF, INF], and each sweep relaxes all five edges in the order listed.","Predict each sweep, and watch where the negative edge 1->2 improves a cost that 0->2 already set, then how that cheaper cost flows down to dst."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]]},"arrays":[{"name":"dist","values":[0,"INF","INF","INF","INF"]}]}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Predict each sweep","title":"Trace the repeated relaxation","workspacePanel":"visualizer","beats":[{"id":"sweep-1-direct","title":"Sweep 1: what does dist[2] become after edge 1->2?","summary":"From [0, INF, INF, INF, INF], edges fire in order: 0->1 (4), 0->2 (5), 1->2 (-3), 2->3 (2), 3->4 (1).","prompt":"0->1 sets dist[1] = 4 and 0->2 sets dist[2] = 5. Then 1->2 reads dist[1] = 4.","options":[{"id":"improves-to-1","label":"It drops to 1, because 4 + (-3) beats the 5 from 0->2","rationale":"0->2 set dist[2] = 5 earlier in the same sweep, but 1->2 then offers dist[1] + (-3) = 4 - 3 = 1, which is below 5, so dist[2] drops to 1. The negative edge gives a cheaper two-hop route the direct edge could not.","isCorrect":true},{"id":"stays-5","label":"It stays 5, since 0->2 already set it","rationale":"Relaxation compares the existing cost with the new offer. 1->2 offers 1, below the 5 from 0->2, so dist[2] improves to 1 within the same sweep.","isCorrect":false},{"id":"becomes-neg3","label":"It becomes -3, the weight of the edge","rationale":"The new cost is dist[1] + w, not w alone. dist[1] is 4, so 1->2 offers 4 + (-3) = 1, not -3.","isCorrect":false}],"answer":"dist[2] drops to 1. 0->2 set it to 5, then 1->2 offered 4 + (-3) = 1, which is smaller, so the negative edge wins. The same sweep then sets dist[3] = 1 + 2 = 3 and dist[4] = 3 + 1 = 4."},{"id":"reach-dst","title":"After sweep 1, what is dist[4]?","summary":"The sweep continues from edge 2->3 to edge 3->4, using each distance currently in the table.","prompt":"Apply the two remaining edge relaxations in order and read the destination entry.","options":[{"id":"four","label":"4, because the cheaper cost at node 2 flows down through 3 to 4","rationale":"2->3 offers 1 + 2 = 3, so dist[3] = 3; then 3->4 offers 3 + 1 = 4, so dist[4] = 4. The single negative edge 1->2 lowered node 2, and that saving carried all the way to the destination.","isCorrect":true},{"id":"nine","label":"9, using the direct cost 5 at node 2","rationale":"By the time 2->3 fires, dist[2] is already 1, not 5, because 1->2 improved it earlier in the same sweep. So node 3 gets 3, not 7, and dist[4] is 4, not 9.","isCorrect":false},{"id":"inf","label":"Still the sentinel, since 4 is too far to reach in one sweep","rationale":"Edges fire in list order within a single sweep, so 0->1->2->3->4 can all relax in this one pass because each edge comes after the one feeding it. dist[4] reaches 4 on sweep 1.","isCorrect":false}],"answer":"dist[4] becomes 4. dist[2] was 1 when 2->3 fired, so dist[3] = 3 and then dist[4] = 4. Because the edges happen to be listed in path order, one sweep was enough to push the cost all the way to dst."},{"id":"settle","title":"Sweep 2: does any edge still lower a cost?","summary":"dist is [0, 4, 1, 3, 4] after sweep 1. This graph has no cycle.","prompt":"Each edge offers dist[u] + w against the current dist[v].","options":[{"id":"no-change","label":"No edge improves anything, so the loop can stop early","rationale":"0->1 offers 4 (not below 4), 0->2 offers 5 and 1->2 offers 1 (not below 1), 2->3 offers 3 (not below 3), 3->4 offers 4 (not below 4). Sweep 2 changes nothing, so every cost has settled, the early-exit fires, and dist[4] = 4 is the answer.","isCorrect":true},{"id":"keeps-dropping","label":"Costs keep dropping every sweep","rationale":"This graph's first sweep already propagated the best route because the edges appear in a helpful order, and checking sweep 2 shows that no edge offers a lower cost. Other edge orders can still improve on later sweeps without any cycle, so the proof here is the no-change sweep itself.","isCorrect":false},{"id":"needs-all","label":"It must run all n-1 sweeps before stopping","rationale":"n-1 is the upper bound. A sweep that changes nothing proves everything has settled, so the loop can stop the moment that happens.","isCorrect":false}],"answer":"Nothing improves on sweep 2. Every edge offers a value no smaller than the current cost, so the costs are settled, the early-exit triggers, and dist[4] = 4 is returned."}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"sweep-1-direct","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]],"current":1,"highlighted":[2],"activeEdges":[[1,2]]},"arrays":[{"name":"dist","values":[0,4,5,"INF","INF"],"current":2}]}},{"id":"reach-dst","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]],"current":3,"highlighted":[4],"activeEdges":[[3,4]]},"arrays":[{"name":"dist","values":[0,4,1,3,4],"current":4}]}},{"id":"settle","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[0,4,1,3,4]}]}}]}},{"id":"pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","title":"Can the relaxation skip the reachability check?","summary":"Dropping the `dist[u]` reachability guard looks harmless: relax on `dist[u] + w < dist[v]` for every edge. It passes the connected examples. Watch it on a graph where an edge leaves a node the source never reaches.","pitfall":"The code relaxes every edge with no guard on whether the source node is reachable. With a finite sentinel for unreachable nodes, sentinel + a negative weight reads as below another sentinel.","workspacePanel":"trace","whyItMatters":"An unreachable node holds the sentinel 10^18, and a negative edge out of it offers 10^18 - 5, which is below the 10^18 at its target, so the target gets a fake near-sentinel cost instead of staying truly unreachable. That value is not exactly the sentinel, so the final check never maps it to 1000000000, and if dst lands on it the answer is garbage. The fix is to skip any edge whose source is still at the sentinel: only relax from a node the source can actually reach.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def cheapest(n: int, edges: list[list[int]], src: int, dst: int) -> int:\n    INF = 1000000000000000000\n    dist = [INF] * n\n    dist[src] = 0\n    for _ in range(n - 1):\n        for u, v, w in edges:\n            if dist[u] + w < dist[v]:\n                dist[v] = dist[u] + w\n    if dist[dst] == INF:\n        return 1000000000\n    return dist[dst]","steps":[{"id":"reach-1","title":"0->1 correctly sets dist[1] = 2","codeLine":8,"summary":"Source is node 0, destination is node 3. Edge 0->1 offers 0 + 2 = 2, below dist[1] = INF, so dist[1] = 2. So far the reachable part is right; nodes 2 and 3 are not reachable from node 0.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[2,3,-5]],"current":0,"highlighted":[1],"activeEdges":[[0,1]]},"arrays":[{"name":"dist","values":[0,2,"INF","INF"],"current":1}]}},{"id":"fake-relax","title":"2->3 fires from an unreachable node","codeLine":7,"summary":"dist[2] is still INF = 10^18 because node 2 is unreachable. With no guard, 2->3 offers 10^18 + (-5) = 10^18 - 5, which is below dist[3] = 10^18, so the check passes and dist[3] is rewritten to 10^18 - 5. The destination, which should stay unreachable, just got a finite-looking cost.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[2,3,-5]],"current":2,"highlighted":[3],"activeEdges":[[2,3]]},"arrays":[{"name":"dist","values":[0,2,"INF","INF-5"],"current":3}]}},{"id":"bad-output","title":"The dst check misses the fake value","codeLine":9,"summary":"The final check maps dist[dst] to 1000000000 only when it equals the sentinel exactly. dist[3] is 10^18 - 5, not exactly the sentinel, so it slips through and the method returns a huge garbage number instead of 1000000000.","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[2,3,-5]],"current":3,"highlighted":[]},"arrays":[{"name":"dist","values":[0,2,"INF","INF-5"],"current":3}]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const INF = unsupportedIntegerLiteral(\"1000000000000000000\");\nconst dist = Array.from({ length: n }, () => INF);\ndist[src] = 0;\nfor (let i = 0; i < (n - 1); i++) {\n    for (const [u, v, w] of edges) {\n        if ((dist[u] + w) < dist[v]) {\n            dist[v] = (dist[u] + w);\n        }\n    }\n}\nif (dist[dst] === INF) {\n    return 1000000000;\n}\nreturn dist[dst];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"10":12,"11":14},"statementBundles":{"8":{"startLine":7,"endLine":10},"10":{"startLine":12,"endLine":13}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const INF = unsupportedIntegerLiteral(\"1000000000000000000\");\nconst dist = Array.from({ length: n }, () => INF);\ndist[src] = 0;\nfor (let i = 0; i < (n - 1); i++) {\n    for (const [u, v, w] of edges) {\n        if ((dist[u] + w) < dist[v]) {\n            dist[v] = (dist[u] + w);\n        }\n    }\n}\nif (dist[dst] === INF) {\n    return 1000000000;\n}\nreturn dist[dst];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":6,"8":7,"9":11,"10":12,"11":14},"statementBundles":{"8":{"startLine":7,"endLine":10},"10":{"startLine":12,"endLine":13}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"long INF = 1000000000000000000L;\nList<long> dist = Enumerable.Range(0, n).Select(_ => INF).ToList();\ndist[src] = 0;\nfor (int i = 0; i < n - 1; i++) {\n    foreach (var item in edges) {\n        int u = item[0];\n        int v = item[1];\n        int w = item[2];\n        if (dist[u] + w < dist[v]) {\n            dist[v] = dist[u] + w;\n        }\n    }\n}\nif (dist[dst] == INF) {\n    return 1000000000;\n}\nreturn checked((int)dist[dst]);","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":9,"8":10,"9":14,"10":15,"11":17},"statementBundles":{"6":{"startLine":5,"endLine":8},"8":{"startLine":10,"endLine":13},"10":{"startLine":15,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"long long INF = 1000000000000000000LL;\nvector<long long> dist = vector<long long>(n, INF);\ndist[src] = 0;\nfor (int i = 0; i < (n - 1); i++) {\n    for (vector<int> item : edges) {\n        int u = item[0];\n        int v = item[1];\n        int w = item[2];\n        if ((dist[u] + w) < dist[v]) {\n            dist[v] = static_cast<long long>((dist[u] + w));\n        }\n    }\n}\nif (dist[dst] == INF) {\n    return 1000000000;\n}\nreturn dist[dst];","lineMap":{"2":1,"3":2,"4":3,"5":4,"6":5,"7":9,"8":10,"9":14,"10":15,"11":17},"statementBundles":{"6":{"startLine":5,"endLine":8},"8":{"startLine":10,"endLine":13},"10":{"startLine":15,"endLine":16}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"long INF = 1000000000000000000L;\nList<Long> dist = new ArrayList<>();\nfor (int index = 0; index < n; index++) {\n    dist.add(((long)(INF)));\n}\ndist.set(src, 0L);\nfor (int i = 0; i < (n - 1); i++) {\n    for (List<Integer> edge : edges) {\n        int u = edge.get(0);\n        int v = edge.get(1);\n        int w = edge.get(2);\n        if ((dist.get(u) + w) < dist.get(v)) {\n            dist.set(v, ((long)((dist.get(u) + w))));\n        }\n    }\n}\nif (dist.get(dst) == INF) {\n    return 1000000000;\n}\nreturn Math.toIntExact(dist.get(dst));","lineMap":{"2":1,"3":2,"4":6,"5":7,"6":8,"7":12,"8":13,"9":17,"10":18,"11":20},"statementBundles":{"3":{"startLine":2,"endLine":5},"6":{"startLine":8,"endLine":11},"8":{"startLine":13,"endLine":16},"10":{"startLine":18,"endLine":19}}}}}},{"id":"edge-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Two input shapes that stress the answer","workspacePanel":"visualizer","body":["The reachability guard handles the unreachable-edge trap you just traced. Two more shapes decide the rest of the answer: a destination the source cannot reach at all, and a source that is already the destination.","One asks what dst reports when no path exists; the other asks whether any relaxation is even needed. Decide what the algorithm returns for each."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"edge-intro-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[1,2,3]],"current":1,"highlighted":[2],"activeEdges":[[1,2]]},"arrays":[{"name":"dist","values":[0,2,5,"INF"]}]}}]}},{"id":"edge-unreachable","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What does dst report when no path reaches it?","summary":"n = 4, src = 0, dst = 3, edges 0->1 (2), 1->2 (3). Node 3 has no incoming edge.","workspacePanel":"visualizer","options":[{"id":"sentinel-out","label":"1000000000, after the sentinel survives every sweep","rationale":"Node 3 has no path from src, and the reachability guard blocks relaxing from any sentinel cost, so dist[3] stays at the sentinel through every sweep. The final check sees dist[3] still at the sentinel and returns 1000000000.","isCorrect":true},{"id":"neg-one","label":"-1, the smallest cost seen anywhere in the graph","rationale":"The answer reads dst specifically. Node 3 is never reached, so its cost is the sentinel, which reports as 1000000000.","isCorrect":false},{"id":"raw-inf","label":"The raw sentinel 10^18, since it was never reached","rationale":"The sentinel is internal. The contract is to report 1000000000 for an unreachable destination, so the final check converts a surviving sentinel before returning.","isCorrect":false}],"answer":"It reports 1000000000. The guard keeps node 3 at the sentinel through every sweep, and the final check maps that surviving sentinel to 1000000000.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"unreachable-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"}],"edges":[[0,1,2],[1,2,3]]},"arrays":[{"name":"dist","values":[0,2,5,"INF"]}]}}]}},{"id":"edge-src-equals-dst","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"What if src already equals dst?","summary":"n = 3, src = 2, dst = 2, with one edge 0->1 (5) that never touches node 2.","workspacePanel":"visualizer","options":[{"id":"zero","label":"0, because the seeding already settles it","rationale":"dist[src] is seeded to 0 before any sweep. When src equals dst, dist[dst] is that same 0, and no edge can lower it below 0 on a graph with no reachable negative cycle. So the answer is 0 with no special branch needed.","isCorrect":true},{"id":"sentinel","label":"1000000000, since no edge reaches node 2","rationale":"An unreached node reports the sentinel, but node 2 is the source, so it was seeded to 0, not left at the sentinel. dist[dst] is 0.","isCorrect":false},{"id":"edge-weight","label":"5, the only edge weight in the graph","rationale":"Edge 0->1 never touches node 2 and cannot change dist[2]. The cost from a node to itself is 0, straight from the seeding.","isCorrect":false}],"answer":"It returns 0. Seeding dist[src] = 0 already settles the src-equals-dst case, so dist[dst] is 0 and no extra branch is needed.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"src-dst-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"}],"edges":[[0,1,5]],"highlighted":[2]},"arrays":[{"name":"dist","values":["INF","INF",0]}]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","summary":"Seed src at 0, relax only from reachable nodes, sweep up to n-1 rounds, then read the destination's cost or the unreachable sentinel.","ctaLabel":"Start coding","workspacePanel":"visualizer","body":["It comes down to four moves. Seed every cost at the sentinel and set the source to 0. For each edge, combine the source's cost with the edge weight to form a candidate. Sweep the edge list up to n-1 times, lowering a target only when its source is already reachable and the candidate is cheaper, and stop early on a sweep that changes nothing. Then read dst: return its cost if it is finite, otherwise the unreachable sentinel.","The picture shows the seeded state before the first sweep: source at 0, every other node at the sentinel. The reachability guard skips any edge whose source is still sitting at the sentinel."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"graph":{"nodes":[{"id":0,"label":"0"},{"id":1,"label":"1"},{"id":2,"label":"2"},{"id":3,"label":"3"},{"id":4,"label":"4"}],"edges":[[0,1,4],[0,2,5],[1,2,-3],[2,3,2],[3,4,1]]},"arrays":[{"name":"dist","values":[0,"INF","INF","INF","INF"]}]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","eyebrow":"Code the sweep","title":"Build the repeated relaxation","summary":"Now build the sweep: seed every cost at the sentinel with the source at 0, form each edge's candidate as dist[u] + w, relax all edges over n-1 passes whenever a reachable source offers something cheaper, then read dst as a finite cost or the unreachable sentinel.","workspacePanel":"code","checkpoints":[{"id":"init-dist","title":"Initialize distances","description":"Set all distances to INF and seed the source distance with zero.","commonMistakes":["Initializing every node to zero","Forgetting to seed the source"],"hint":"Only the source is known at cost zero before relaxation starts.","semanticSpec":{"intent":"Initialize weighted shortest-path distance state.","doneWhen":"The distance array is filled with a sentinel and `dist[src]` is set to zero.","shouldFailWhen":"This step should fail if there is no distance state or if the source is not seeded.","roles":["distance array","source node","infinity sentinel"],"mustProve":["The code initializes weighted distance state.","The source node has distance zero."],"mustNotAccept":["Starting every node as reachable.","Using edge weights as initial distances."],"equivalentVariants":["Use a large integer sentinel for unreachable distances."],"proofSnippets":[{"id":"py-cheapest-signed-path-init-dist","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        return -1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"initializes_weighted_distance_state","scope":"init-dist","readMode":"graph-value-query-v1"}]}},{"id":"compute-candidate","title":"Compute edge candidates","description":"For each reachable edge source, combine its distance with the edge weight before writing an update.","commonMistakes":["Using the destination distance as the candidate base","Ignoring the edge weight when comparing distances"],"hint":"The candidate distance is dist[u] + w for edge u -> v.","semanticSpec":{"intent":"Compute weighted Bellman-Ford candidates from edge entries.","doneWhen":"The code scans weighted edges inside the pass loop and compares a source-distance-plus-weight candidate against the destination distance.","shouldFailWhen":"This step should fail if edges are scanned without a weighted candidate comparison.","roles":["edge scan","source distance","edge weight","candidate distance"],"mustProve":["The code binds source, destination, and weight from each edge.","A candidate distance combines the source distance with the edge weight."],"mustNotAccept":["A loop over edges that ignores the weight.","A candidate based on the destination distance."],"equivalentVariants":["Store the candidate in a local variable before comparing.","Compute the candidate inline inside the comparison."],"proofSnippets":[{"id":"py-cheapest-signed-path-compute-candidate","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        for _ in range(n - 1):\n            for u, v, w in edges:\n                if dist[u] == INF:\n                    continue\n                cand = dist[u] + w\n                if cand < dist[v]:\n                    pass\n        return -1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"computes_weighted_edge_relaxation_candidate","scope":"relax-candidate","readMode":"graph-value-query-v1"}]}},{"id":"relax-edges","title":"Relax all edges repeatedly","description":"Run up to n - 1 passes over all edges and update better destination distances.","commonMistakes":["Relaxing each edge only once","Using the destination distance before checking source reachability"],"hint":"A shortest simple path can use at most n - 1 edges.","semanticSpec":{"intent":"Apply Bellman-Ford edge relaxation over repeated full edge scans.","doneWhen":"The code scans all weighted edges inside a pass loop and writes smaller candidate distances.","shouldFailWhen":"This step should fail if edges are not repeatedly relaxed.","roles":["pass loop","edge scan","candidate distance","distance update"],"mustProve":["The code repeatedly scans weighted edges.","The code updates a destination distance when a smaller candidate is found."],"mustNotAccept":["Only checking direct edges from the source.","Updating distances without source reachability."],"equivalentVariants":["Use an early-exit flag when a pass makes no updates."],"proofSnippets":[{"id":"py-cheapest-signed-path-relax-edges","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        for _ in range(n - 1):\n            for u, v, w in edges:\n                if dist[u] == INF:\n                    continue\n                cand = dist[u] + w\n                if cand < dist[v]:\n                    dist[v] = cand\n        return -1"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"repeats_weighted_edge_relaxation","scope":"run-bf","readMode":"graph-value-query-v1"}]}},{"id":"return-result","title":"Return destination cost","description":"Return the finalized destination distance or the unreachable sentinel.","commonMistakes":["Returning the whole distance array","Treating negative finite costs as unreachable"],"hint":"Only INF means unreachable; a negative distance can be a valid cheapest cost.","semanticSpec":{"intent":"Return the relaxed scalar metric for the destination.","doneWhen":"The code returns the destination distance if finite and the unreachable sentinel otherwise.","shouldFailWhen":"This step should fail if the method returns all distances or a stale candidate.","roles":["destination node","finite distance","unreachable sentinel"],"mustProve":["The code reads the relaxed destination distance.","The code distinguishes finite distance from the unreachable sentinel."],"mustNotAccept":["Returning zero for unreachable destinations.","Returning the edge count instead of cost."],"equivalentVariants":["Use `1000000000` as the unreachable output sentinel."],"proofSnippets":[{"id":"py-cheapest-signed-path-return-result","language":"python","code":"class Solution:\n    def cheapestSignedPath(self, n: int, edges: list[list[int]], src: int, dst: int) -> int:\n        INF = 10**18\n        dist = [INF] * n\n        dist[src] = 0\n        for _ in range(n - 1):\n            for u, v, w in edges:\n                if dist[u] == INF:\n                    continue\n                cand = dist[u] + w\n                if cand < dist[v]:\n                    dist[v] = cand\n        OUT_INF = 1000000000\n        if dist[dst] == INF:\n            return OUT_INF\n        return int(dist[dst])"}]},"validation":{"type":"semantic","validator":"familyFact","params":[{"family":"graph","fact":"returns_relaxed_metric_result","scope":"return-result","readMode":"graph-value-query-v1"}]}}]},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","summary":"One cost per node, relaxed over n-1 sweeps from a single source, then dst read off as a finite cost or the unreachable sentinel.","workspacePanel":"code","takeaways":[{"title":"Never lock a node","body":"A negative edge can undercut a cost after it looked final, so greedy settling reports stale values; relaxing every edge over repeated sweeps lets late shortcuts still take effect."},{"title":"n-1 sweeps, because a shortest path has at most n-1 edges","body":"Each sweep extends every path by one edge, so n-1 sweeps settle every honest shortest path; the whole cost is O(n*e), with an early exit the moment a sweep changes nothing."},{"title":"Guard the sentinel, then read dst","body":"Relaxing only from reachable nodes keeps an unreachable dst at the sentinel, which reports as 1000000000; a finite dist[dst] is the cheapest cost, even when it is negative."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
