Long-Awaited Party#11715

Long-Awaited Party (Editorial)

Problem Author:

Oleksandr Tymkovych

Editorial by:

Oleksandr Tymkovych

Let's solve the problem for one query l=1,~r=n, when all the friends attend the party.

We may consider each bit independently, so if we solve the problem for a_i \in \{0,1\} then we can also solve for arbitrary a_i.

Now, let's work with the formula:

\sum_{p \in \mathcal{S}_n}\sum_{k=1}^{n}\left(a[p_1] \oplus a[p_2] \oplus \dots \oplus a[p_k]\right) = \sum_{k=1}^{n}\sum_{p \in \mathcal{S}_n}\left(a[p_1] \oplus a[p_2] \oplus \dots \oplus a[p_k]\right)

We know that a[p_1] \oplus a[p_2] \oplus \dots \oplus a[p_k] = 1 only if the number of ones among a[p_1], \dots, a[p_k] is odd. We are not interested when that term equals zero, since it contributes nothing to our total sum.

Let denote the number of ones in our array.

The formula simplifies to

\texttt{answer} = \sum_{k=1}^{n}\sum_{x=0}^{\lfloor\frac{\texttt{cnt}-1}{2}\rfloor}\left[\binom{k}{2x+1} \cdot \binom{n-k}{\texttt{cnt}-(2x+1)} \cdot \texttt{cnt}! \cdot (n - \texttt{cnt})!\right]

since we choose which ones will be before and which ones will be after . Also, we multiply by factorials, since the ones and zeroes are indistinguishable, so we can permute them as we wish.

\texttt{answer} = \texttt{cnt}! \cdot (n - \texttt{cnt})! \sum_{k=1}^{n}\sum_{x=0}^{\lfloor\frac{\texttt{cnt}-1}{2}\rfloor}\left[\binom{k}{2x+1} \cdot \binom{n-k}{\texttt{cnt}-(2x+1)}\right]
= \texttt{cnt}! \cdot (n - \texttt{cnt})! \sum_{x=0}^{\lfloor\frac{\texttt{cnt}-1}{2}\rfloor}\sum_{k=1}^{n}\left[\binom{k}{2x+1} \cdot \binom{n-k}{\texttt{cnt}-(2x+1)}\right]
= \texttt{cnt}! \cdot (n - \texttt{cnt})! \sum_{x=0}^{\lfloor\frac{\texttt{cnt}-1}{2}\rfloor} \binom{n+1}{\texttt{cnt}+1} \tag{$\color{red}{\ast}$}
= \texttt{cnt}! \cdot (n - \texttt{cnt})! \cdot \left\lceil\frac{\texttt{cnt}}{2}\right\rceil \cdot \binom{n+1}{\texttt{cnt}+1}
= \texttt{cnt}! \cdot (n - \texttt{cnt})! \cdot \left\lceil\frac{\texttt{cnt}}{2}\right\rceil \cdot \frac{(n+1)!}{(\texttt{cnt}+1)!\cdot (n-\texttt{cnt})!}
= \left\lceil\frac{\texttt{cnt}}{2}\right\rceil \cdot \frac{(n+1)!}{\texttt{cnt} + 1}

Hence, the formula depends on and . The number of ones on the segment may be pre-calculated with partial sums.

In () we used the Chu-Vandermonde identity: \displaystyle \sum_{m=0}^{n} \binom{m}{j} \binom{n-m}{k-j} = \binom{n+1}{k+1}.

Proof: imagine a binary sequence of length n+1 with exactly k+1 ones (the right part counts the number of such sequences). To show a bijection with the left part, consider the (j+1)-th one in the (m+1)-th position in the sequence.