ProgrammingVery hardTCS NQT · Accenture

Ropes are to be merged into one. Merging two ropes of lengths a and b costs a + b and yields one rope of length a + b. Ropes have lengths 5, 9, 12, 13, 16, 45. The greedy method below is used. What is the total cost?

Ropes are to be merged into one. Merging two ropes of lengths a and b costs a + b and yields one rope of length a + b. Ropes have lengths 5, 9, 12, 13, 16, 45. The greedy method below is used. What is the total cost?
repeatedly take the two shortest ropes, merge them, add the cost to total
until one rope remains
Print total
  1. A. 239
  2. B. 100
  3. C. 224
  4. D. 416

Correct answer: C. 224

Always merging the two shortest ropes minimises the cost because each length is paid once for every merge it takes part in. A list-order merge is worse, the single root alone is 100, and a max-heap merges the largest ropes and pays far more.

More Pseudocode and Code Tracing questions

Exams that ask this topic