I recently encountered a problem that requires to compute $$$\sum_{i=0}^{n-1} \sum_{j=i+1}^{n-1} \sum_{k=j+1}^{n-1} a_i a_j a_k$$$ in $$$O(n)$$$. My friend __declspec, (orz), uses prefix sums to compute it, which takes many time to implement, and also easy to have bugs (to me). I found the product of the 3 elements familiar in the multinomial theorem, so I tried applying it to the problem.
The multinomial theorem
From Wikipedia, the theorem states
where
Example
In the case where $$$n=2$$$,
where
In the recent problem 1637D - Yet Another Minimization Problem, $$$\sum\limits_i \sum\limits_{j>i} {(a_i + a_j)^2}$$$ shows up. According to the editorial (thanks for the amazing problems and editorial), it can be simplified as follow,
The middle term can be simplified,
The middle term can be simplified with some change of indices,
Thus,
The main dish — triple summation
First we let $$$S = \sum\limits_i {a_i}$$$. By the multinomial theorem,
Rearranging,
Comparison to prefix sums
Which do you think is better? Comment your thoughts below!
Why stop at n=3?
By the multinomial theorem,
At this point we can define $$$S_j = \sum\limits_i {a_i^j}$$$. Note that:
Putting them altogether,
Thus,
Well, using prefix sums might be better instead of going through these tedious calculations...
Conclusion
Using either prefix sums or multinomial theorem can compute the above summations in $$$O(n)$$$. Although the multinomial theorem solution requires tedious calculations, it can be used to simplify some summations in problems like the above example problem.
Thanks for reading and now let's take a rest to enjoy your daily dose of waifu.