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- A. 4
- B. 33
- C. 15
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- A truck carries at most 10 boxes. The box types are given as (units per box, number of boxes): (5, 3), (4, 2), (3, 4), (2, 5). The greedy…
- The greedy below repeatedly increases the smallest element of the array [3, 1, 2] by 1, three times in total. What is the minimum value of…
- For the function gcd(a, b) written by the procedure below, what is printed for gcd(252, 105)? (The procedure uses repeated remainder…
- The Fibonacci numbers F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) satisfy gcd(F(m), F(n)) = F(gcd(m, n)). The procedure below uses this…
- The procedure below computes the last digit of 7^100 by starting from d = 1 and multiplying by 7, keeping only the last digit, once for…
- The number of ways to write 20 as p + q with p and q prime and p <= q is counted by the procedure below, which tries p = 2 to 10 and sets…