ProgrammingVery hardTCS NQT · Accenture

Ropes of lengths 1, 2, 3, 4 and 5 are merged two at a time with cost equal to the sum of the two lengths. The greedy merges the two shortest ropes each time (a min-heap is used). What is the total cost printed?

Ropes of lengths 1, 2, 3, 4 and 5 are merged two at a time with cost equal to the sum of the two lengths. The greedy merges the two shortest ropes each time (a min-heap is used). What is the total cost printed?
heap = [1, 2, 3, 4, 5]
while heap has more than one rope
    a = remove smallest; b = remove smallest
    total = total + a + b; insert a + b
end while
Print total
  1. A. 4
  2. B. 33
  3. C. 15
  4. D. 50

Correct answer: B. 33

Merges go 1+2=3, 3+3=6, 4+5=9 and 6+9=15, which totals 33. Counting the merges gives 4, merging the two longest ropes pays 50, and summing the lengths gives 15.

More Pseudocode and Code Tracing questions

Exams that ask this topic