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.
orz
orz
orz
hatsune miku real!!!!!
I don't think this is very useful, at least in the applications that you have shown. Both approaches consume $$$\mathcal{O}(n\cdot k)$$$ space and run in the same complexity, but the prefix sums approach is very straightforward and doesn't require any math work by hand.
Yes, I agree with you. I hope to see some applications of this method in some future CP math problems.
I think this is the approach of many people starting CP like me. A simpler example is to calculate $$$\sum_{i=l}^ra_i$$$, if one doesn't know about prefix sum they are likely to work that out with maths formula. Sometimes handworks help reducing space and time complexit, too.
Pratice problem using multinomial theorem
Thank you for the link :)
I find it easier without using multinomial sums (and it's faster too), but nevertheless interesting to see another approach.
Yes, very fun to see different methods can give the same result.
Here is another implementation using prefix sums, and it seems to me quite easy to write:
You're on the right path but with more practice in pattern recognition, you should be able to figure out the formula without even thinking about the multinomial theorem for small powers.
For large powers, a general formula using the sums of powers can be constructed by GEM rather than by hand.