Data Structures & AlgorithmsVery hardICPC regional · graph round

Problem: Run Bellman-Ford style negative-cycle detection (all distances start at 0, V - 1 rounds, then one extra check) on 3 vertices with edges (0,1,4), (1,2,-2), (2,1,-1). What is printed?

Problem: Run Bellman-Ford style negative-cycle detection (all distances start at 0, V - 1 rounds, then one extra check) on 3 vertices with edges (0,1,4), (1,2,-2), (2,1,-1). What is printed?
def neg(n, edges):
    d = [0] * n
    for _ in range(n - 1):
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v] = d[u] + w
    for u, v, w in edges:
        if d[u] + w < d[v]:
            return True
    return False
print(neg(3, [(0, 1, 4), (1, 2, -2), (2, 1, -1)]))
What is printed?
  1. A. False
  2. B. None
  3. C. True
  4. D. 0

Correct answer: C. True

The cycle 1 to 2 to 1 has weight -2 + (-1) = -3, so it is negative and relaxations never stop improving. Starting distances at 0 acts as a virtual source connected to every vertex.

More Coding Interview Problems questions

Exams that ask this topic