Data Structures & AlgorithmsVery hardProduct company OA

Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?).

Problem: Shortest route where exactly one road may be used at half price (one coupon). Dijkstra on states (junction, coupon used?).
import heapq
def coupon(n, edges, s, t):
    g = [[] for _ in range(n)]
    for a, b, w in edges: g[a].append((b, w)); g[b].append((a, w))
    INF = 10**18; d = [[INF, INF] for _ in range(n)]
    d[s][0] = 0; h = [(0, s, 0)]
    while h:
        c, u, used = heapq.heappop(h)
        if c > d[u][used]: continue
        for v, w in g[u]:
            for nu, nc in ((used, c + w), (1, c + w // 2)) if not used else ((1, c + w),):
                if nc < d[v][nu]: d[v][nu] = nc; heapq.heappush(h, (nc, v, nu))
    return min(d[t])
E = [(0, 1, 4), (1, 3, 4), (0, 2, 2), (2, 3, 20), (3, 4, 1)]
print(coupon(5, E, 0, 4), coupon(5, E[:4], 0, 3))
What is printed?
  1. A. 9 8
  2. B. 7 6
  3. C. 7 12
  4. D. 13 6

Correct answer: B. 7 6

Each junction is split into two layers; using the coupon moves from layer 0 to layer 1 with cost ⌊w/2⌋. First query: 0 → 1 → 3 → 4 with the coupon on a road of weight 4 costs 2 + 4 + 1 = 7, cheaper than halving the 20-road (2 + 10 + 1 = 13). Second (target 3, without the last road): 2 + 4 = 6. Simply halving the heaviest road of the ordinary shortest path can fail when a longer path contains a much heavier road; the layered graph considers every choice and is O((V + E) log V).

More Coding Interview Problems questions

Exams that ask this topic