← All problems

Another Popcount Problem

Codeforces · Round #1105 (Div. 2) · Problem A ↗

Problem

Given two integers nn and kk (1≤n,k≤106)(1 \leq n, k \leq 10^6), construct a sequence a1,a2,…,aka_1, a_2, \ldots, a_k with ∑ai≤n\sum a_i \leq n maximizing the total number of 11-bits across all the aia_i (the total popcount).

Output that maximum.

Initial Observations
  1. Binary.
  2. Make all 11's?
  3. (111…1)×k(111\ldots1) \times k?
  4. Greedy.
IdeaGreedily use all-ones numbers, packed as evenly as possibleAC

First thoughts: if some aia_i has bb one-bits, you clearly want it to be as small as possible while keeping those bb bits.

Key Observation

Any aia_i with bb one-bits can be replaced by the smallest number with bb one-bits — the "all ones" number 2b−12^b - 1. The popcount is unchanged and the sum only shrinks, which can never hurt: it leaves more room under nn to squeeze in more bits elsewhere. We use this implicitly throughout.

As a reminder, the numbers 2b−12^b - 1 are exactly the ones that look like a run of 11's in binary:

b = 1:   2^1 - 1  =  1   =  1
b = 2:   2^2 - 1  =  3   =  11
b = 3:   2^3 - 1  =  7   =  111
b = 4:   2^4 - 1  =  15  =  1111
Problem Transformation

I didn't do this explicitly while solving, but the observation above really flips the problem: for a given popcount, how small can the sum be? If it fits under nn, that popcount is achievable.

For example, 13=1101213 = 1101_2 and 7=11127 = 111_2 both contribute 33 to the popcount, but 77 is smaller — and the slack might buy another bit (with n=13n = 13: taking 1313 spends the whole budget for 33 bits, while [7,1][7, 1] gets 44 bits with budget to spare).

Key Observation

In an optimal solution, we can assume every aia_i is of the form 2bi−12^{b_i} - 1 for some bi≥0b_i \geq 0.

Examine Examples

This problem is almost easier to see by example than to explain rigorously. Take n=6,k=2n = 6, k = 2: [5,1][5, 1] has sum 66 and 33 bits; [7][7] doesn't use both slots; but [3,3][3, 3] has sum 66 and 44 bits — the best. Playing with a few of these suggests the winning shape: all-ones numbers, packed as evenly as possible.

Should you ever hold a 11 and a 77 when you could hold 33 and 33 instead? It seems you never really want one number to be much bigger than another. We can prove this with an exchange argument:

Key Observation

Writing each ai=2bi−1a_i = 2^{b_i} - 1, we can assume ∣bi−bj∣≤1|b_i - b_j| \leq 1 for all i,ji, j: the bit-counts are as balanced as possible.

Proof.

Suppose bj≥bi+2b_j \geq b_i + 2. Move one bit from the big number to the small one: bj→bj−1b_j \to b_j - 1, bi→bi+1b_i \to b_i + 1. The popcount is unchanged, and the sum changes (the −1-1's cancel) by

(2bi+1+2bj−1)−(2bi+2bj)=2bi−2bj−1<0,\left(2^{b_i+1} + 2^{b_j-1}\right) - \left(2^{b_i} + 2^{b_j}\right) = 2^{b_i} - 2^{b_j-1} < 0,

since bj−1≥bi+1b_j - 1 \geq b_i + 1. So balancing strictly decreases the sum at equal popcount — always a good trade.

∎

This is the main insight. All the bib_i differ by at most one, so there is some level b∗b^* where every item has b∗b^* bits except for a few upgraded to b∗+1b^* + 1. Greedily, b∗b^* should be the largest level at which kk items even fit:

Key Observation

Let b∗b^* be the largest bb with (2b−1)⋅k≤n(2^b - 1) \cdot k \leq n — equivalently b∗=⌊log⁡2(n/k+1)⌋b^* = \lfloor \log_2(n/k + 1) \rfloor. In an optimal solution every item has b∗b^* bits, except some that have b∗+1b^* + 1.

Key Question

How many items get the extra bit?

Greedy again: give every item b∗b^* bits, then upgrade items one at a time while the budget lasts. Upgrading one item from 2b∗−12^{b^*}-1 to 2b∗+1−12^{b^*+1}-1 increases the sum by exactly 2b∗2^{b^*}. So with leftover=n−k(2b∗−1)\text{leftover} = n - k(2^{b^*}-1) still unspent, the number of upgrades is ⌊leftover/2b∗⌋\lfloor \text{leftover} / 2^{b^*} \rfloor. (This is automatically less than kk — if all kk items could be upgraded, b∗+1b^* + 1 would contradict the maximality of b∗b^*.)

Write It Out

The rest is writing the formulas out carefully.

Algorithm
# largest b with (2^b - 1) * k <= n — increment rather than take logs
b = 0
while (2**(b+1) - 1) * k <= n:
    b += 1
 
leftover = n - k * (2**b - 1)
upgrades = leftover // (2**b)        # each extra bit costs 2^b
 
print(k * b + upgrades)

Implementation notes: no logarithms needed — incrementing bb is simpler and avoids floating point. Use 64-bit integers for the products.

Generate and Test

The first greedy ideas here are relatively obvious and obviously correct — the work was checking the mechanics, not finding alternatives.

Review

The answer is k⋅b∗+⌊(n−k(2b∗−1))/2b∗⌋k \cdot b^* + \lfloor (n - k(2^{b^*}-1)) / 2^{b^*} \rfloor, where b∗b^* is the largest bb with (2b−1)k≤n(2^b-1)k \leq n. The path:

  1. Use all-ones numbers. Any value can be replaced by 2b−12^b - 1 with the same popcount and a smaller sum — equivalently, flip the problem: minimize the sum for a given popcount. [1][2]
  2. Balance the bit-counts. An exchange argument (move a bit from a big number to a small one) shows all bib_i can differ by at most one. [3]
  3. Pick the highest level that fits: b∗b^* = largest bb with (2b−1)k≤n(2^b - 1)k \leq n; everyone gets b∗b^* bits. [4]
  4. Spend the leftover on upgrades at 2b∗2^{b^*} apiece — maximality of b∗b^* guarantees fewer than kk of them.

(My accepted submission.)

References

Problem-solving techniques used:

Generate and Test

Easy enough that the first greedy ideas are obviously correct — don't spend time inventing alternatives, just run with it.

Problem Transformation

Given a number of bits, minimize their sum — a flip of the problem (arguably also a way of working backwards). I never framed it explicitly; I just kept trying to shrink the sum, and that assumption drove the next few insights.

Examine Examples

Playing with a few small cases leads to the same insights.

Write It Out

The ending required a bit of math — powers of two, potentially logarithms, edge cases. Not hard, but it needed careful bookkeeping.

Topics: