Graph Theory37 sections · 1633 units
Open in Course

High Score - Implementation

Complete solution

Here is the complete solution:

negatedEdges = [(u, v, -w) for (u, v, w) in edges]
dist = array of size n + 1, all infinity
dist[1] = 0

for round from 1 to n - 1:
    for (u, v, w) in negatedEdges:
        if dist[u] + w < dist[v]:
            dist[v] = dist[u] + w

canReachN = BFS from nodes that can still relax
if canReachN[n]:
    print -1
else:
    print -dist[n]

Detect if infinite score is possible via negative cycle reaching nn.