Editorial for TSSPC Contest 1 P5 - Trick or Trail
Submitting an official solution before solving the problem yourself is a bannable offence.
The first two subtasks can be solved using Dynamic Programming. Every point can only be reached from points
or
. Therefore, the amount of paths you can take to
is equal to the paths to
and
summed together. Store the paths to
in a
array, and recursively sum to find the total amount of paths to
The last subtask requires knowledge of properties of Pascal's triangle. Notice that by the above sum property, the grid follows a pattern similar to Pascal's Triangle. Another property is that the th number in the
th row (the first row is row
) is equal to
. A proof of this property can be found in the footnote. By this property, the amount of paths can be found by computing
Thus we are presented with a new problem, how do we calculate the value effectively? Taking the factorials and then dividing would cause an overflow as . The solution requires taking mod after every factorial. We can perform division with mod by using the property of modular inverse. Given
, if
(the numbers are coprime), then there exists an integer
such that
.
is the modular inverse. Dividing by
is equivalent to multiplying by
, the modular inverse. Because
is a prime number,
will always be coprime and there always exists a modular inverse.
One way to find the modular inverse is by looping through all values . However, we have to loop through at most
operations to find the inverse. We can do one better by using Fermat's little theorem, which states that for a prime
,
, and
if
coprime. By Fermat's little theorem, we get that
, which means
is the inverse of
.
But this is still not fast enough!!!!! We will have to do at most operations if we do the exponential normally! Next, we use binary exponentiation, which is done by computing the mods of
to the exponent of a power of
. For example if we want to compute
, we just multiply together
and
. Here is the implementation of binary exponentiation in pseudocode:
exp = 1
x = 1000000005
while x > 0{
if x & 1 == 1{
exp = exp * b % 1000000007;
}
a = a*a % 1000000007;
x = x >> 1;
}
return exp
Footnote To prove the Pascal triangle property, we can use Pascal's formula, which states that . Try proving that for yourself! It can also be solved by considering a set of
up operations and
right operations. The amount of paths is equal to the amount of distinct permutations of the set, which also gives
Comments