Back to the 2022 paper

Module 3: Graph and Tree Algorithms

20227m

What is negative weight-cycle? Write Bellman-Ford algorithm to find single source shortest distance of a directed graph.

Worked SolutionAI Assisted

Negative Weight Cycle & Bellman-Ford Algorithm

Negative Weight Cycle

Directed cycle CC with sum ∑e∈Cw(e)<0\sum_{e\in C} w(e) <0. In such graph, shortest path from source to vertices reachable from CC is undefined (−∞-\infty) because traversing cycle repeatedly reduces path weight arbitrarily. Example: a→ba→b -2, b→ab→a -1 → cycle -3.

Without negative cycles, shortest simple paths well-defined (≤ V−1V-1 edges).

Bellman-Ford — Single Source Shortest Paths (SSSP) with Negatives

BellmanFord(G, s):
  dist[s]=0; dist[v]=∞ for v≠s; parent[v]=NIL
  repeat V-1 times:
    for each edge (u,v)∈E:
      if dist[u]+w(u,v) < dist[v]:
        dist[v]=dist[u]+w(u,v); parent[v]=u
  // detect negative cycle
  for each edge (u,v):
    if dist[u]+w(u,v) < dist[v]:
      return "Negative cycle reachable from s" (and retrieve cycle via parent)
  return dist, parent

Correctness: After ii iterations, dist[v]dist[v] = shortest path using ≤ ii edges. After V−1V-1, all simple paths considered. If still relaxable → ≥ VV edges → must contain cycle → negative.

Complexities: Time O(VE)O(VE) (list) / O(V3)O(V^3) (matrix), Space O(V)O(V). Superior to Dijkstra which fails with negatives; slower but handles them.

Finding All Negative Cycles: Add super source s′s' with 0 edges to all vertices, run once to detect any cycle in graph.

Similar questions

Official AppAndroid App

PYQDeck for Android

Solve BEU previous-year exam papers anywhere, anytime. Fast search, offline paper viewing, and step-by-step solutions designed specifically for your phone.