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?- A. False
- B. None
- C. True
- 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
- Problem: A directed graph has edges 0->1, 0->2, 1->2, 1->3, 2->3. Let A be its adjacency matrix. How many walks of exactly 3 edges go from…
- Problem: Undirected graph on 5 vertices has edges (0,1), (1,2), (2,0), (2,3), (3,4). Count the bridges by deleting each edge in turn and…
- Problem: Topological order by DFS finishing times (reverse postorder) for the DAG adj = {0: [1, 2], 1: [3], 2: [3], 3: []} on 4 vertices…
- Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'. python def lcssub(a, b): best = 0 dp =…
- Problem: How many (possibly overlapping) occurrences of the pattern 'ana' are in 'banana'? python s = 'banana' p = 'ana' print(sum(1 for i…
- Problem: Each element of [2, 3, 1, 1, 4] is the maximum jump length from that index. What is the minimum number of jumps to reach the last…