Table of Contents

ExplanationImplementation

Official Editorial

Explanation

A little thing to notice that helps us in the right direction is that a possible test case can have queries that ask for one specific number, like

100 100

This motivates a prefix sum approach, where we calculate the answer for each possible integer and answer queries with a prefix sum array.

To actually count the number of non-palindromic arrays that sum to an integer (which we'll refer to as xx from now on), we can use complimentary counting.

To count the total number of arrays that sum to xx, period, we evaluate the following summation:

l=1x((xl)+(l1)l1)\sum_{l=1}^x \binom{(x-l)+(l-1)}{l-1}

In this summation, we sum over all possible lengths ll of the array, and then use stars and bars to count how many arrays of length ll sum to xx. The initial subtraction of ll is to account for that all elements must be positive.

This expression then simplifies to

l=1x(x1l1)=l=0x1(x1l)=2x1\begin{align*} \sum_{l=1}^x \binom{x-1}{l-1} &= \sum_{l=0}^{x-1} \binom{x-1}{l} \\ &= \boxed{2^{x-1}} \end{align*}

The binomial theorem is applied to simplify the summation.

It remains to count the number of palindromic arrays that sum to xx. For this, there's two cases to consider: xx being even and xx being odd.

If xx is even, then it's possible to have an even-length palindromic array. Each half must sum to x2\frac{x}{2} and since the two are basically identical, there's 2x212^{\frac{x}{2}-1} possible palindromic arrays of this form. However, we can also form an odd-length array by taking some even number from xx initially and setting it as the center element. This gives us a grand total of

1+2x21+i=1x/212(x2i)/211+2^{\frac{x}{2}-1}+\sum_{i=1}^{x/2-1} 2^{(x-2i)/2-1}

The 11 at the front is another edge case when we put all of xx as the middle. But anyways, notice that this actually simplifies to 2x22^{\frac{x}{2}}! Pretty cool, huh?

If xx is odd, though, we can't have an even-length palindromic array. We can only take an odd amount from xx and set it as the center, giving us

1+i=0x/212(x2i1)/211+\sum_{i=0}^{\lfloor x/2 \rfloor-1} 2^{(x-2i-1)/2-1}

This also simplifies like the one we did previously, only this time it's to 2x122^{\frac{x-1}{2}}.

Implementation

Time Complexity: O(Q+N)\mathcal{O}(Q+N), where NN is the maximum value of rr.

Python

MOD = 10**9 + 7
MAX_VAL = 10**5
two_pows = [1]
for _ in range(1, MAX_VAL + 1):
two_pows.append((two_pows[-1] * 2) % MOD)
pref_sums = [0]
for i in range(1, MAX_VAL + 1):
if i % 2 == 0:

C++

#include <bits/stdc++.h>
using namespace std;
const int MOD = 1e9 + 7;
const int MAX_SUM = 1e5;
int mod(long long a) { return (a + MOD) % MOD; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!