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
- A. 239
- B. 100
- C. 224
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Stock prices by day: 3, 8, 2, 9, 1, 6. One share may be bought once and sold once later (later day only). The procedure below runs. What…
- Currency notes are paid out greedily from the largest denomination down, using as many notes of each denomination as possible. For amount…
- A number is given as the digit string 1432219. Exactly 3 digits must be deleted (the digits keep their order) so that the remaining number…
- The same stack method is applied to the string 5317 with exactly 2 digits deleted, but now the aim is the LARGEST number. The procedure…
- Children have greed values 7, 8, 9, 10 and cookies have sizes 5, 6, 7, 8, 8. A child is content if the cookie given is at least his greed…
- Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval…