← All problems

KitayutaMart

TopCoder · SRM 648 (Div. 1) · 550 ↗

Problem

There are KK types of apples. For a fixed type of apple, ii, there is an unlimited number of apples of that type. The cost of buying an apple of type ii depends on how many apples of type ii you have already bought. In particular, the first apple of type ii costs ii yen. The second apple of type ii costs 2i2i yen, the third costs 4i4i yen, etc. In general, the jthj^{th} apple of type ii costs i⋅2j−1i \cdot 2^{j-1} yen.

You would like to purchase a total of NN apples. Among all the ways of purchasing NN apples, you choose the set of apples that costs the least, in total. For this set of apples, what is the most expensive apple you purchase? (The answer is guaranteed to be unique. Also, print your answer modulo 1,000,000,0071,000,000,007)

Note that 1≤N,K≤1091 \leq N,K \leq 10^9.

Initial Observations
  1. Binary numbers, powers of 2
  2. Greedy
  3. Binary Search
  4. Sort all apples, take the smallest first
  5. "Search for a pattern"
  6. SQRT-Decomposition?
  7. Different algorithm depending on if K is large or small?

Review

This was a really hard problem for me. I was unable to solve it in the contest. Even after inspecting Petr's solution, it took me a while to understand and derive the actual answer for myself. Here is my summary of the approach to solve the problem -- hopefully we will be able to recreate the "correct train of thought" needed to solve this problem.

The first initial observation is that "the algorithm" for choosing apples is fixed. You will always buy the cheapest apple at any point in time, until you have NN total apples. The answer is the value of last apple you buy. Remember this, because we can use this fact throughout the analysis.

Now, we cannot simply "enumerate" or "list" all the apples explicitly, as NN and KK are too large to do this. But is there any efficient way to determine what this "last apple" would be?

At this point, we work backwards. What if we knew the final value of the apple? Or, what if we had a "guess" vv for what this value might be? Is there any way of checking whether vv is a good guess or a bad one? In theory, the answer is yes. Particularly, let's suppose we were able to count the total number of apples with value ≤v\leq v. If this number is strictly smaller than NN, then we can be sure that vv is too small of a guess. This is because of our "initial observation": we will always choose the cheapest apples until we get NN of them. And if there are less than NN apples with value ≤v\leq v, then we must pick at least one apple with a value >v> v in order to get NN apples in total. Conversely, if the answer we get is at least NN, then we know vv is a good guess, and we will stop at vv or earlier than vv.

This leads to a "binary search" idea. Fix a vv, and count the total number of apples with value ≤v\leq v. If this is less than NN, try a bigger vv. Otherwise, try a smaller vv.

There are two issues with this, though. First, vv might be extremely large! The numbers in the input can become as large as 210000000002^{1000000000} or bigger. The second issue is: "How do we count the total number of apples with value ≤v\leq v?"

To answer both of these questions, and to (hopefully) lead to further insights, we both look at examples and draw a picture. Consider an example where N=30N = 30 and K=10K = 10 (you might also try smaller examples; we may use bigger examples later). To "illustrate", we draw an K×NK \times N matrix, where cell (i,j)(i,j) has value i⋅2j−1i \cdot 2^{j-1} (the cost of the jthj^{th} copy of apple ii). This matrix is drawn below.

Furthermore, suppose that we have a guess for vv. For example, let us guess that v=224v = 224. Then we would choose all apples with value ≤v=224\leq v = 224. In the matrix below, we have coloured/shaded the related cells.

j=1j=1j=2j=2j=3j=3j=4j=4j=5j=5j=6j=6j=7j=7j=8j=8j=9j=9j=10j=10
1248163264128256512
2481632641282565121024
36122448961923847681536
4816326412825651210242048
51020408016032064012802560
61224489619238476815363072
714285611222444889617923584
8163264128256512102420484096
9183672144288576115223044608
10204080160320640128025605120

(The shaded cells of the original figure — the apples with value ≤224\leq 224 — are shown in bold.)

You can verify that there are 6161 apples with value ≤224\leq 224. Since 61≥N=3061 \geq N = 30, this vv is large enough.

At this point, we can play around with different values of vv, and try to note down any observations we find. Here are a couple of these key observations (it's often helpful to write out our findings):

  1. Without loss of generality, our minimum vv will always be an element in the table, of the form i⋅2j−1i\cdot 2^{j-1} for positive integers ii and jj (with 1≤i≤K1 \leq i \leq K). If we have a guess for vv that is not an actual element of this form, we can simply decrease vv until we find a guess that is of this form. For example, 224=7⋅25224 = 7\cdot 2^5.
  2. Given a fixed vv, consider the columns in the matrix from left-to-right, and we notice a pattern: there will be a few columns where all the cells are selected, followed by columns in which the number of selected cells decreases by (approximately) half from column-to-column.

To some readers, these may seem almost obvious. But focusing on these observations helps us to answer the questions we had earlier! In particular, we can use this "pattern" to quickly count the total number of apples with values ≤v\leq v. Firstly, we write v=i⋅2j−1v = i \cdot 2^{j-1} with 1≤i≤K1 \leq i \leq K (which is possible from Observation 1). Then we consider the "pattern" of cells that would be selected when looking at values ≤v\leq v. In columns 1,2,3,...,j−11,2,3,...,j-1, all K cells must be chosen. Then in column jj, we get exactly ii cells. In column j+1j+1 we get ⌊i2⌋\left\lfloor\frac{i}{2}\right\rfloor cells, and in column j+2j+2 we get ⌊i4⌋\left\lfloor\frac{i}{4}\right\rfloor cells, and so on. This goes to 0 in a logarithmic number of steps.

We can formalize this argument. Let

S(n):=n+⌊n2⌋+⌊n4⌋+⌊n8⌋+⌊n16⌋+⋯ .S(n) := n + \left\lfloor\frac{n}{2}\right\rfloor + \left\lfloor\frac{n}{4}\right\rfloor + \left\lfloor\frac{n}{8}\right\rfloor + \left\lfloor\frac{n}{16}\right\rfloor + \cdots.

Then, for a number v=i⋅2j−1v = i \cdot 2^{j-1} (with ii the largest possible such that 1≤i≤K1 \leq i \leq K), there are exactly

(j−1)K+S(i)(j-1)K + S(i)

apples with value ≤v\leq v.

I omit the proof, but the idea can be seen from the picture. One important detail must be discussed however: ambiguity. Some numbers, like 512512 appear multiple times in the table. This corresponds to many different ways of writing 512512 as i⋅2j−1i \cdot 2^{j-1}. For the proof to work (and this also turns out to be the most intuitive assumption as well), we assume that jj is as small as possible (equivalently, that ii is as large as possible) among all representations of the same number. This is the occurrence in the "left-most" occurrence of the number vv in the matrix. For example, we write 512512 as 8⋅268 \cdot 2^{6} rather than 4⋅274 \cdot 2^7 or 1×291 \times 2^9.

We notice that S(n)S(n) can be counted in logarithmic time (since the parameter nn is cut in half iteratively), and the (j−1)K(j-1)K part can be computed in Θ(1)\Theta(1) time. So this answers one of our earlier questions about being able to efficiently count the number of apples for a given guess vv.

If the numbers were smaller, we could do a binary search, and we'd be done. However, we need a way to quickly make guesses for vv without explicitly having to represent it -- since the number vv can be really large. Also, in our counting formula above, we assumed vv had a certain form: i⋅2j−1i \cdot 2^{j-1}.

To deal with these issues, we represent the number vv using the most natural idea based on the data we have. We always represent vv as a pair (i,j)(i,j), meaning that v=:i⋅2j−1v =: i \cdot 2^{j-1}, and ii is as large as possible without being bigger than KK.

At this point, I think a cleverly crafted search, similar to "Gallop search" or something like that, might be able to help us. We are simply looking for the parameters (i,j)(i,j) that yield a minimum vv so that

(j−1)K+S(i)≥N.(j-1)K + S(i) \geq N.

One problem, however, is that we don't have a nice bound on jj. How large of a jj would be necessary? How small of a jj would be sufficient?

Now that we have a nice formula, we can use it to find the bounds we are interested in. We know that i≤Ki \leq K. In fact, we know that K2<i≤K\frac{K}{2} \lt i \leq K, because we chose ii to be the largest among all representations. (If i≤K2i \leq \frac{K}{2} then we could let i′=2ii' = 2i and j′=j−1j' = j-1 to get a better representation of our number vv. This would usually be a contradiction.) Anyway, putting this together with our formula, gives us that:

(j−1)K+S(K2)<(j−1)K+S(i)≤(j−1)K+S(K)(j-1)K + S\left(\frac{K}{2}\right) \lt (j-1)K + S(i) \leq (j-1)K + S(K)

Now, we want to find (i,j)(i,j) such that (j−1)K+S(i)≥N(j-1)K + S(i) \geq N. What is the smallest jj we can have? Well, we can apply the second inequality above and assume i=Ki = K (since this is the largest choice of ii for any fixed jj). From this we would get:

(j−1)K+S(K)≥N(j-1)K + S(K) \geq N

or

j≥⌈N−S(K)K⌉+1j \geq \left\lceil\frac{N - S(K)}{K}\right\rceil + 1

And note that substituting i=Ki=K was valid. If ii is smaller than KK, then we would need an even larger value of jj to compensate. Hence, we have proven the following theorem: For any v=i⋅2j−1v = i \cdot 2^{j-1} with 1≤i≤K1 \leq i \leq K, if there are at least NN apples with value ≤v\leq v, then:

j≥j∗:=⌈N−S(K)K⌉+1j \geq j^* := \left\lceil\frac{N - S(K)}{K}\right\rceil + 1

This gives us a lower bound on jj for valid (i,j)(i,j) pairs. But we are actually interested in an upper bound on jj. If we draw more pictures, look at more examples, or go back to our formulas, we realize that this value j∗j^* actually tells us a lot more than we thought! We can actually prove another lemma: if j>j∗j > j^* and i>K2i > \frac{K}{2}, then the value (j−1)K+S(i)(j-1)K + S(i) will be at least (j∗−1)K+S(K)(j^*-1)K + S(K). So any minimal vv will have j≤j∗j \leq j^*. This is best shown with a picture. I omit such a picture, or a detailed explanation/proof, but it also follows from the inequalities above. I encourage the reader to prove why this is true.

In any case, we have therefore discovered that, once we have found j∗j^*, our "optimal" (minimal) vv will be of the form i⋅2j∗−1i \cdot 2^{j^*-1} for some 1≤i≤K1 \leq i \leq K. With this information, we can use a simple binary search on ii, checking whether (j∗−1)K+S(i)≥N(j^* - 1)K + S(i) \geq N at each step or not. Once we've found our minimal i∗i^*, we output the answer v=i∗⋅2j∗−1v = i^* \cdot 2^{j^*-1} (modulo the number 1,000,000,0071,000,000,007, as asked in the problem statement.)

Pseudo-code:

Algorithm
S(n):
  answer := 0
  while(n > 0):
    answer += n
    n = n / 2
 
  return answer
 
lastPrice(N,K):
  Let jstar = ceil((N - S(K)) / K) + 1  # The optimal j^*
 
  low = 1
  high = K
  while low < high                      # binary search
    i := (low + high) / 2
    if (jstar - 1)*K + S(i) >= N:       # how many apples no more than v = i*2^(j*-1)?
      high = a
    else
      low = a+1
 
  istar = low                           # same as high
  return istar * power(2, jstar - 1) MODULO 1,000,000,007

Key observations:

References

Problem-solving techniques used:

Ask for Help

I was unable to solve this problem in contest. So it was beneficial to look at the solution and try to re-construct it for myself. Learning from other people is a good way to improve. Hopefully I have learned something! And same to you as well, dear reader!

Work Backward

I would say this is the most important problem-solving technique used here. Instead of asking "How do we find the value of the last apple?", we ask the question "Can we decide whether a particular value vv can possibly be the last apple?" This reversing of the question changes it from a discovery problem to a decision problem. And in this case, it leads to a binary search idea, because we suspect that we can quickly answer the related question: "Is my guess for vv too big or too small?" This immediately leads us onto the right track.

Problem Transformation

We followed the idea of guessing a particular vv and checking if it is too big or too small. This leads to the following method: "Count the total number of apples with value ≤v\leq v. If this is less than NN, then vv is too small. Otherwise, vv is big enough." This turned our decision problem into a counting problem. Intuitively, because of the structure of the numbers, it feels like we may be able to answer this question efficiently.

Examine Examples

After having the above problem transformation, its best to look at a few examples with different NN,KK and guesses for vv. I admit I did not do this much during the contest (time pressure!) but I followed this approach when I came through this problem a second time. It is sure to lead to some insights!

Draw a Picture

The description of the problem leads itself to a nice "matrix" picture. Using this pictorial representation makes a lot of "proofs" easier later on, and also makes it fairly easy to find the key observations we are looking for.

Exploit the Constraints

All numbers are given to us in the form i⋅2j−1i \cdot 2^{j-1} (by definition of the problem). So, when looking for a nice way to represent our value vv, it was convenient to always right it in this form.

Learning points:

Topics:

Related problems:

Coming soon.