This problem can be solved in several ways. We will discuss the author’s solution here.

For each ii from 11 to yy, we will generate how many ways we can take an array of size nn such that the elements are between xx and yy and the bitwise-and value of the array is ii.

DP approach: (TLE expected)

Let dp[i][j]dp[i][j] be the number of ways we can generate an array of size ii such that the bitwise-and of the array is jj, now the transition will look like

dp[i][p&q]=dp[i][p&q]+dp[i1][q]dp[i][p\&q]=dp[i][p\&q]+dp[i-1][q]

here pp is an integer between xx and yy and qq is an integer between 11 and yy, and this represents a new element pp being added to an array of size i1i-1 that previously had bitwise-and value of qq.

Notice that the number of ways can be big that it won’t fit in normal 6464 bits integers, we will need structures that can work with larger numbers(BigInt). But there’s an issue Let’s say we are working with an array of size nn, then the number of ways can contain ~n3n*3 digits. as nn can be up to 910189*10^{18}, we can’t store numbers with this many digits.

Observation: For a particular value of xx and yy, let’s the answer for length ii be AiA_i​, then AiAjA_i \leq A_j for all iji \leq j, and AinfinityA_{infinity} will be the bitwise-and value of all integers between xx and yy. Now it can be proven that for all i(yx+1)i \geq (y-x+1)AiA_i​ will be the same as AinfinityA_{infinity} as once AiA_i reaches that number it won’t change. Turns out that in the given constraints AiA_i reaches that minimum value within ~700700 length. So, if a query is given with n>700n>700, we can just output that minimum value without any calculations. Otherwise, we can run the DP to generate the result.

The complexity of this approach will be O(yy700B)O(y*y*700*B), here BB is the time taken for BigInt operations. This will be too slow to pass.

Convolution approach:

Notice that the transition explained in the DP approach is just and-Convolution. Let’s have a polynomial PP of degree yy where Pi=1P_i=1  for xiyx \leq i \leq y, 0 otherwise. Now, and-Convolution of PP with itself n1n-1 times will essentially give us PnP^n, now PinP^n_i represents the number of ways we can generate an array of size nn such that the bitwise-and of the array is ii and that is what we are after. Do and-Convolution using Fast Walsh Hadamard Transforms and you will have a fast solution. Do the BigInt multiplications in FWHT using Fast Fourier transform and you have a faster solution.

Time Complexity: O(700ylog(y)B)O(700*y*log(y)*B)

Space Complexity: O(y)O(y)

Bonus Problem:

Given the upper limit of yy, can you find out what value of xx, yy  will take the longest array to reach AinfinityA_{infinity}?

Statistics

42% Solution Ratio
EgorKulikovEarliest, Sep '22
nusuBotFastest, 0.9s
EgorKulikovLightest, 786 kB
mdshadeshShortest, 1427B
Toph uses cookies. By continuing you agree to our Cookie Policy.