Mathematics Combinatorics
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle.
More formally, there are gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let’s number the places in the order they occur in the circle by numbers from 0 to , let the gnome sitting on the place have coins. If there is an integer i (0 ≤ i < n) such that , then Tanya is satisfied.
Count the number of ways to choose so that Tanya is satisfied. As there can be many ways of distributing coins, print the remainder of this number modulo . Two ways, a and b, are considered distinct if there is index i (0 ≤ i < 3n), such that ai ≠ bi (that is, some gnome got different number of coins in these two ways).
Read the question with I/O specifications at codeforces.com.
Think of subtracting from total approaches instead of finding not cases, in combinatorics.
Try selecting triplets to form triangles as per the required condition.
In how many ways can you select the coin pairs (2, 2, 2) and (1, 2, 3)?
Read about faster modular exponentiation.
a mod b won’t always be equal to a%b. a%b gives the remainder of a divided by b.
Instead of directly calculating cases for i (0 <= i < n) satisfying , we can find cases for where , a relatively easier solution and then subtract the value from the total number of cases.
Going by Tanya’s love of triplets, we can select three equally spaced points each to make independent triangles, such that the points are of the form , and for 0 <= i < n.
It now comes down to the cases where all the selected triangles produce a vertex value sum of 6. This can be calculated as permutations of the pairs and .
Total cases of pair per triangle = 1
Total cases of pair per triangle = 3x2x1 = 6
Hence, the cases where a triangle can have vertex value sum as 6 is 7. With a total count of triangles, the number of cases equal .
Total number of cases can be calculated as 3 raised to the number of ways of choosing . Since the gnomes are arranged in a circular order with no initial of final numbering, there are 3n cases of choosing .
Hence, the answer becomes mod . Since n varies from 0 to 105, there needs to be a faster way to calculate the power value. Read about faster modular exponentiations. Through faster modular exponentiation technique, we can obtain and . Subtracting the values and finding the gives the answer. But will not always work. Why? Because the % operator gives the remainder and not the mod value. Both the remainder and mod value remain same for positive numbers, but can break down in case of negative numbers.
The correct all encapsulating way of the mod operation, for a mod b would be (a%b + b)%b.
Written by Nandakishore