Hints for SRM 596, D1, 250-Pointer (IncrementAndDoubling)

James S. Plank

Tue Sep 2 14:44:26 EDT 2014
Problem Statement.
First, consider an element i in isolation. The minimum number of operations to create i will be to double it as many times as possible. For example, consider the number 5. You can create it with four operations: add-double-double-add. There's no way to do it with fewer. How about 12? That will be add-double-add-double-double.

Now, think about the following two functions:

For example, Adds(1) is one, and Adds(2) is one. Adds(3) is two, and Adds(4) is one.

Doubles(1) is zero, and Doubles(2) is one. Doubles(3) is one, and Doubles(4) is two.

Now, for each element A[i], suppose you know Adds(A[i]) and Doubles(A[i]). Do you see how you calculate the return value? Think about it before you move onto the next paragraph.

It is going to be the sum of Adds(A[i]) for all A[i], plus the maximum Doubles(A[i]). That is because you can double all elements at the same time.

You can use bit arithmetic, if you want, to calculate Adds(i) and Doubles(i). That would be good practice for bit arithmetic. However, when I did it, I used a for() loop for Doubles(i), and I wrote Adds(i) recursively. It's good practice: