Editorial for LCC '24 Contest 1 S5 - Exponential Sweets


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

For simplicity, let the array be

[a, b, c, d]

After one second:

[a, a+b, a+b+c, a+b+c+d]

Two seconds:

[a, 2a+b, 3a+2b+c, 4a+3b+2c+d]

Three seconds:

[a, 3a+b, 6a+3b+c, 10a+6b+3c+d]

It's easy to recognize these coefficients as diagonals in Pascal's Triangle, which are related to Combinations.

To understand why this is the case, consider the grid where each row t is the array a at time t:

{a_1}_1, {a_1}_2, {a_1}_3, {a_1}_4

{a_2}_1, {a_2}_2, {a_2}_3, {a_2}_4

{a_3}_1, {a_3}_2, {a_3}_3, {a_3}_4

{a_4}_1, {a_4}_2, {a_4}_3, {a_4}_4

How much will {a_1}_1 contribute to the sum in {a_4}_4? Each path of only right and down moves between {a_2}_1 and {a_4}_4 represents one "propagation" of {a_1}_1 to {a_4}_4 from repeated prefix-summing. It's a bit abstract, but moving right is choosing to continue the propagation along the row in a specific frame of time, while moving down is choosing to move one second forward.

So, each term a_i's contribution to the final sum is {(N+T-i) \choose T}.

Now, how do we calculate this mod 1e9+7?

Recall that n \choose x = \frac {n!} {x!(n-x)}

The multiplication is quite straightforward, and the factorial can be precomputed. However, to perform the modular division, say, to divide by x, you have to multiply by the modular inverse of x in mod 1e9+7.

One way to find this modular inverse is using Fermat's Little Theorem, which states that a^{p-1} = 1 mod p for primes p. By extension, a^{p-2} = {\frac {1} {a}} mod p. That means to divide by x in mod 1e9+7, it is equivalent to multiplying by x^{p-2} mod p. To calculate this power, the following binary exponentiation method can be used:

long long fastPow(long long base, long long expo, long long mdl){
    long long ret = 1;
    while (expo > 0){
        if (expo&1) ret = (ret*base) % mdl;
        base = (base*base) % mdl;
        expo >>= 1;
    }
    return ret;
}

Comments

There are no comments at the moment.