0% found this document useful (0 votes)
5 views33 pages

tama-editorial

Uploaded by

gabatnibac
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views33 pages

tama-editorial

Uploaded by

gabatnibac
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

TAMa 2024 Editorials

Cisco Ortega

Contents
A) Nostalgia 2

B) Holy Molé 5

C) The Amazons in their Prime 8

D) SRS 11

E) Sussy Spanning Trees 14

F) Digivisible 17

G) Supersetter 20

H) Expected Value of Civil War 23

I) Stratosphere 27

J) Roll the Dice 31

1
A) Nostalgia

Subtasks 1 & 2

Just code it.

2
Subtask 3

You can create a “sliding window” of sorts. Let wt = st + st−1 + · · · + st−(k−1) .


Then, you can compute the value of sn from the value of sn−1 in just O(1)
by using two windows. See the following diagram.

You can compute the leftmost window in O(k) time, then each subsequent
window can be computed from the previous one in O(1) time by subtracting
out the old leftmost element and adding in the new rightmost element (of
the new window).

Thus, the ultimate solution is O(n + k).

3
Subtask 4

Google quickly evaluate linear recurrence relations comp prog or


something similar and you’ll discover the standard technique of how to do so
using fast matrix exponentiation. You can ask around for good tutorials on
this technique.

This solves the problem in O(k 3 lg n).

For an example of what to expect, consider the following matrix-vector equa-


tion for k = 3. Let an = s1 + s2 + · · · + sn be the value we want to compute.
    
1 2 3 2 1 0 st+4 s(t+4)+1
1 0 0 0 0 0
 st+3  s(t+3)+1 
   

0 1 0 0 0 0 st+2  s(t+2)+1 
    
= .
0 0 1 0 0 0 st+1  s(t+1)+1 
 
    
0 0 0 1 0 0  st   st+1 
0 0 0 1 0 1 at at+1

Repeated application of the above matrix-vector equation then (inductively)


leads us to the following relation:
 n    
1 2 3 2 1 0 s4 s4+n
1 0 0 0 0 0
 s3  s3+n 
   

0 1 0 0 0 0 s2  s2+n 
     
  =
0 0 1 0 0 0 s1  s1+n 
 
     
0 0 0 1 0 0 s0  s0+n 
0 0 0 1 0 1 a0 a0+n

which will give us the value of an that we want (if we speed up repeated
matrix multiplication using fast exponentiation).

Your solution should smell like this, or at least something close to this, though
you may choose to have slightly different “implementation details” with the
matrix you choose to construct.

4
B) Holy Molé

Subtasks 1 & 2

For small n, write a brute forcer that directly simulates the problem (or do
that on pen and paper).

(The brute forcer program can be directly used to solve Subtask 1)

Bowl Touched by Angel 0 Touched by Angel 1 Touched by Angel 2


1 Y Y Y
2 N Y Y
3 Y N Y
4 N N Y
5 Y Y N
6 N Y N
7 Y N N
8 N N N

Then, make the following observation:

• There is a one-to-one correspondence between the 2n bowls, and the 2n


possible subsets of “Which angels touched this bowl?”

You can prove this by induction.

So, to count how many bowls have been touched by r angels, we can equiva-
lently count how many ways there are to choose r out of the n angels (to be
the ones to touch those bowls). Thus, the answer is
n  
X n
.
r=m
r

Because n is small, you can compute the binomial coefficients by just about
any method and it’ll probably work out.

5
Subtask 3

Recall that what we want to compute is each of the following:


 
n
(mod p)
r
n!
= (mod p).
r!(n − r)!

But we can precompute all values of k! for k from 1 to n in just O(n) time—
use the fact that k! = k · (k − 1)!

We can also precompute the modular multiplicative inverses of each


of the factorials using Fermat’s Little Theorem or the Extended Euclidean
Algorithm.

Thus, after these precomputations, each binomial coefficient can be computed


in O(1) time by direct use of the factorial formula, leading to an O(n) solution
overall.

6
Subtask 4

Do the digits of n and m look peculiar? Note that m is really close to n/2.
Specifically, m − n/2 = 106 only.

By leveraging the symmetry of the binomial coefficients, you only need to


compute this middle bit that ranges from n − m to m (exclusive of those
endpoints), from which you can derive the actual answer we want.

For example, suppose n = 8 and m = 6. In the diagram below, we break


the sequence of binomial coefficients into three parts. Due to symmetry, we
know that the two orange parts are equal (and the value we desire is one of
these orange parts).

We know the sum of all the binomial coefficients is 28 . We can subtract out
8
+ 84 + 85 (the central blue part), then divide the result by two (to get
  
3
the total of just one orange part).

We only have to evaluate 2 × 106 binomial coefficients for the “central blue
part” of our actual problem, which sounds reasonable. But we still need to
evaluate gigantic binomial coefficients very quickly.

The key is that p = 107 + 19 is also quite small, and also it is prime. So,
leverage this small prime modulus. Here are some theorems you could use:

• Lucas’ Theorem (relates binomial coefficients with modulo)

• Wilson’s Theorem (relates factorials with modulo)

7
C) The Amazons in their Prime

Subtasks 1 & 2
n n
In one session, Maxi completes k
reps and Mini completes k
reps.

So, just directly compute


X X lnm
M=
ℓn ≤n≤rn ℓk ≤k≤r
k
k

and X X jnk
m=
ℓn ≤n≤rn ℓk ≤k≤r
k
k

then compute M − m.

8
Subtask 3

Combine both summations into one.


X X l n m j n k
M −m= − .
ℓ ≤n≤r ℓ ≤k≤r
k k
n n k k

However, nk and nk are almost exactly the same, except one rounds up
   

and the other rounds down. In fact, they are only exactly the same when k
divides n exactly and there is no remainder. So,
(
lnm jnk 0, k divides n
− =
k k 1, otherwise.

So, rewrite the above summation as


X X
(0 if k divides n, else 1)
ℓn ≤n≤rn ℓk ≤k≤rk

But, reasoning with divisors is easier than reasoning about non-divisors, so


rewrite the above as:
X X
(1 − (1 if k divides n, else 0))
ℓn ≤n≤rn ℓk ≤k≤rk
X X
= (rn − ℓn + 1)(rk − ℓk + 1) − (1 if k divides n, else 0).
ℓn ≤n≤rn ℓk ≤k≤rk
X
= (rn − ℓn + 1)(rk − ℓk + 1) − (count of divisors of n that are in [ℓk , rk ]).
ℓn ≤n≤rn

Thus, for each n from ℓn to rn , we want to count how many of its divisors
lie in the range [ℓk , rk ], which can be computed in O(rn lg rn ) by a slight
modification of a standard divisor sieve.

9
Subtask 4

It can be shown that if we can solve the following problem:


X X
(1 if k divides n, else 0)
1≤n≤N 1≤k≤K

(that is, both: n ranges from 1 to N , and k from 1 to K) then we can solve
the original problem (kind of similar to 2D prefix sums’ flavor).

Let’s unpack how the divisor sieve works, mathematically. It’s just an inter-
change of summations:
X X X X
(1 if k divides n, else 0) = (1 if k divides n, else 0)
1≤n≤N 1≤k≤K 1≤k≤K 1≤n≤N
X
= (count of multiples of k that are in [1, N ]).
1≤k≤K

It turns out this is nicer, because enumerating multiples is much easier than
finding divisors. The multiples of k go: k, 2k, 3k, . . . , therefore:
X X N 
(count of multiples of k that are in [1, N ]) = .
1≤k≤K 1≤k≤K
k

We can evaluate this sum in O( N ) using the following “standard” fact:

• Let √
N be fixed and let k vary. Then, the expression Nk takes on only
 

≈ 2 N different values:

◦ Each of k = 1, 2, 3, . . . , N yields a different unique value of Nk
 

◦ For each of v = 1, 2, 3, . . . , N , consider the equation Nk = v;
 

the solutions in k consist of some contiguous range of integers.



Brute force the contributions√ of the terms with k = 1, 2, 3, . . . , N . Then,
for each v = 1, 2, 3, . . . , N , if you can count how many k there are such
that Nk = v (and k ≤ K), then you can determine how many times each of
 

these v should be added to the sum.

10
D) SRS

Subtasks 1 & 2

Just directly generate the first n terms of the SRS.

Note that the entries in the spreadsheet consist of the terms in

(s1 + s2 + s3 + · · · + sn )(s1 + s2 + s3 + · · · + sn ).

So from now on, we’ll only care about computing the sum of the first n entries
in the SRS. Just square that result to get the true final answer.

Fun fact: In the OEIS, you’ll find that the SRS’ “proper” name is the
Golomb sequence!

11
Subtask 3

Naively compute the first few terms of the sequence, just like you would for
Subtasks 1 and 2. These first few terms tell us more about an even longer
prefix of the sequence.

More precisely, the first t terms of the sequence allow us to then infer proper-
ties about the first ti=1 si terms of the sequence, because we know the SRS
P

should look like this:

• First, s1 occurences of 1 (so we can add s1 × 1 to the total sum)

• Then, s2 occurences of 2 (so we can add s2 × 2 to the total sum)

• Then, s3 occurences of 3 (so we can add s3 × 3 to the total sum)

• Then, s4 occurences of 4 (so we can add s4 × 4 to the total sum)

• Then, s5 occurences of 5 (so we can add s5 × 5 to the total sum)


.
• ..

Concretely, for example, knowing that the first five terms are [1, 2, 2, 3, 3]
allows us to deduce that the first 1 + 2 + 2 + 3 + 3 = 11 terms
are [1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5] (the appearances of the values up to 5).
Pt
Let t be the first index such that i=1 si ≥ n. Then, the sum of the first n
terms of the SRS consists of
t−1
X
si × i + (some “incomplete” portion of the subsegment of t’s)
i=1

It turns out that t ≈ 5.4 × 108 is enough to reach n = 1014 .

12
Subtask 4

Take this reasoning and apply it one level deeper. As a concrete example:

• We compute that s4 = 3. This means that that the number 4 appears


3 times in the sequence. In particular:
◦ Note that s1 +s2 +s3 = 5, which means we have already appended
5 terms into the sequence so far (that is, it currently looks like
[1, 2, 2, 3, 3])
◦ That means the subsegment of [4, 4, 4] we append will run from
index 6 until index 8

• That means we know numbers 6 through 8 each appear 4 times, which


means we can predict that later on in the sequence, we will see a part
that looks like [...6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8...]—these are all the sub-
segments that each consist of repeating a number four times, and we
know those repeated numbers are 6 and 7 and 8.

In general:

• Suppose we have directly computed si , for some i.

• From here, we can compute the ℓ such that sj = i for all j ∈ [ℓ, ℓ + si ).

• From here we know then that there is a part of the sequence that goes,

ℓ, ℓ, . . . , ℓ, (ℓ + 1), (ℓ + 1), . . . , (ℓ + 1), . . . (ℓ + si − 1), (ℓ + si − 1), . . . , (ℓ + si − 1),


| {z } | {z } | {z }
i times i times i times

That is, knowing the first t terms of the sequence then lets us compute the
first ti=1 i × si terms of the sequence. Just as before, take the first t such
P

that ti=1 i × si ≥ n. Then, the sum of the first n terms in the SRS is again
P

“sum of contiguous runs + some incomplete subsegment at the end”.

It turns out that t that is just a little bit bigger than 107 is enough to reach
n = 1018 using this method.

13
E) Sussy Spanning Trees

Subtasks 1 & 2

Googling counting spanning trees leads us to the Wikipedia page for


spanning trees, which contains Cayley’s formula: The number of spanning
trees of the complete graph with n vertices is nn−2 .

So, just directly evaluate the sum


N
X
nn−2 (mod m).
n=1

Remember to use fast exponentiation so that each term can be computed in


O(lg n) time only.

14
Subtask 3

The modulus is not prime. So, let’s do a standard technique in Number


Theory: prime factorize m, compute the value modulo each prime power, and
then combine the results together using the Chinese Remainder Theorem.

We prime factorize,

693789912465408 = 219 × 33 × 11 × 472 × 2017

and note that all the prime powers are small.

Note these two things:

rr−2 ≡ (r mod m)r−2 mod m

and, if gcd(r, m) = 1, then

rr−2 ≡ r(r−2) mod φ(m) mod m

where φ is Euler’s totient function (this is Euler’s Theorem). If gcd(r, m) ̸= 1,


recall that our plan is to take moduli that are prime powers—for large enough
r that are divisible by p, we have that rr−2 mod pk all become 0.

The sequence of bases is periodic modulo m, and the sequence of exponents


is (eventually, mostly) periodic modulo φ(m). Combining these insights, the
overall sequence is eventually periodic, with period at most lcm(m, φ(m)).

We can apply standard period-bashing techniques to compute each sum mod-


ulo each prime power, in linear time of the period (so overall, the running
time is quadratic for each prime power).

15
Subtask 4

We’re still going to use the Chinese Remainder Theorem. We prime factorize,

693789912465408 = 222 × 3 × 5 × 11 × (106 + 3).

The largest prime factor is now too large for quadratic time solutions.

Let’s hone in on this fact:

rr−2 ≡ (r mod m)r−2 mod m.

Now, what if we focus on all terms in the sequence that have the same
remainder r modulo m? Concretely, for example, suppose m = 9, and we
look at adding up only the terms that are congruent to r = 4, modulo 9:

42 + 1311 + 2220 + 3129 + . . . ≡ 42 + 411 + 420 + 429 + . . . mod 9


2 0 9 18 27
≡ 4 (4 + 4 + 4 + 4 + . . . ) mod 9
2 0 9 1 9 2 9 3
≡ 4 (4 + (4 ) + (4 ) + (4 ) + . . . ) mod 9.

This is a geometric series with common ratio 49 , and so it can be evaluated


in logarithmic time! Be careful about the cases where gcd(r − 1, m) ̸= 1,
because then r − 1 would not be invertible.

Sum up, for each possible remainder r = 1, 2, . . . , m − 1, the geometric series


consisting of the terms congruent to r (modulo m). The common ratio is rm ,
and the initial term is rr−2 . The number of terms in the geometric series of
some r is not hard to find. Sum all the results together.
m−1
X
rr−2 (1 + rm + (rm )2 + (rm )3 + · · · + (rm )something ).
r=1

This now gives a solution that runs in linearithmic time for each prime factor.

16
F) Digivisible

Subtask 1

You can solve this ad hoc with pen and paper.

• If the number has a 2, then it must be the last digit.

• If the number has a 5, then it must be the last digit.

This makes it tractable as a classic “How many n-digit numbers satisfy this
property...?” introductory combinatorics problem.

17
Subtask 2

There are only 33 + 34 + · · · + 316 possible numbers to consider, which is not


that many. Just write a backtracking program that enumerates all of them,
and test each one for digivisibility.

18
Subtasks 3 & 4

You can maybe come up with some ad hoc casework solution for Subtask 3
which uses the choose function (considering there are divisibility tests for 3
and 6 and 9). But I’ll just jump to talking about the general method now.

Consider this simpler task: How many n-digit numbers using only the digits
from some set S are divisible by m?

This has a pretty classical solution using DP. Construct the number digit-by-
digit, at each step maintaining only the value modulo m of the prefix you’ve
constructed so far. Your state should look something like dp(i, r), where i
is the index of the digit we’re currently at, and r ∈ [0, m) is the value of the
prefix so far (modulo m).

For the transition, consider each possible next digit to append. To append
a new digit, recall that concatenating d to the end of some number n is
equivalently to performing 10n + d.

For digivisibility, we just need to modify this solution slightly. This is enough
to solve Subtask 3.

• Keep track of the value of the prefix so far, modulo m := 2520, which
is lcm(1, 2, . . . , 9).
◦ It can be shown that if d | m, then: n mod d = (n mod m) mod d.

• Also include in our state a bitmask mask which keeps track of which
digits we’ve used so far, since this tells us the digits whose divisibility
we need to check when we’re done constructing the number.

To extend it to Subtask 4, where ℓ and r are not powers of 10 any more,


we just need to include an extra boolean parameter in order to do standard
“digit DP” things (you can ask around for a good digit DP tutorial).

The total number of states comes out to be len(r) × lcm(1, 2, . . . , 10) × 29 × 2,


which comfortably passes.

19
G) Supersetter

Subtasks 1 & 2

Just code it.

For subtask 2, you can use either backtracking or bitmasking to enumerate


all possible partitions of the digits.

20
Subtask 3

Suppose we have a subsegment that ranges from indices ℓ to r inclusive. Re-


gardless of how we choose to partition the rest of the digits, this subsegment
always contributes the same value to the total sum.

For example, suppose we have 1234567890 and focus on what if 3456 formed
a subsegment. Then, the number would look something like

????(34563456)????????

That is, whenever 3456 is a subsegment, it always contributes 3456345600000000


to the sum. There are eight trailing zeros because there are four digits that
come after 3456 in the original number—regardless of how those are parti-
tioned, it will always result in eight digits coming after the 34563456 part.

Next, we need to find out how many partitions there are that have e.g. 3456
as one contiguous block. This is not too hard either—it consists of, indepen-
dently, determining how to partition the digits to its left, and determining
how to partition the digits to its right.

For example, there are 22−1 ×24−1 partitions of the digits of 1234567890 that
have 3456 as a contiguous block, therefore we must add 3456345600000000
to our sum a total of that many times.

Putting that all together, we have a formula for the contribution of some
[ℓ, r] subsegment, so we can just do a summation that ranges over all O(s2 )
such subsegments:
s X
X s
duplicate(n[l..r]) × 10appropriate no. of trailing zeros
×
l=1 r=ℓ

2max(0, no. of digits to its left−1)


× 2max(0, no. of digits to its right−1)

Even if you implement these functions somewhat naively, cubic time solutions
should also be acceptable.

21
Subtask 4

Take the idea from Subtask 3 one step further. For each individual index i,
what is the contribution of the digit at this index i to the overall sum?

We once again consider all subsegments [ℓ, r] that contain i. For example,
suppose we have 1234567890 and focus on the digit 4, and suppose we con-
sider all cases where 3456 form a subsegment. Then, the contribution of
specifically 4 in this case is:

????(?4???4??)????????

In this case, similar to before: the values of ℓ and r determine the number
of trailing zeros in the contribution of the digit and of the duplicated digit.
So, we get a similar summation as the one in Subtask 3:
s X
X s
i X
duplicate(n[i], ℓ, r) × 10appropriate no. of trailing zeros
×
i=1 l=1 r=i

2max(0, no. of digits to its left−1)


× 2max(0, no. of digits to its right−1)

Fully write out all of the terms shown above, and then just do a lot of pen-
and-paper algebra on summations: interchange their order, perform index
shifts, factor out terms independent of the dummy variable, etc. etc. After
a lot of work, you should eventually up with something like this:
s
X s
X
n[i] · (some geometric series) + n[i] · (some other geometric series)
i=1 i=1

(or possibly more, depending on how messy you are with handling edge cases)
where each geometric series can be evaluate in logarithmic time, using its
summation formula (and modular multiplicative inverses).

This yields a solution which runs in linearithmic time (with respect to the
number of digits).

22
H) Expected Value of Civil War

Subtasks 1 & 2

Just code it.

For subtask 2, you can use either backtracking or bitmasking to enumerate


all possible ways to choose n/2 mercenaries.

23
Subtasks 3 & 4

First things first, you can generate primes using the Sieve of Eratosthenes.

Now, onto the actual problem. Let s be the sum of the first n prime numbers.
Then, express sum(T ′ ) as s − sum(T).

Let H be the set of all n/2 sized subsets of the first n prime numbers. Now,
we just do summation algebra with the given expression.
X X
(sum(T ) − sum(T ′ ))2 = (2 sum(T ) − s)2
T ∈H T ∈H
X
= (4 sum(T )2 − 4s sum(T ) + s2 )
T ∈H
X X X
=4 sum(T )2 − 4s sum(T ) + s2 1.
T ∈H T ∈H T ∈H

So, the problem is reduced to solving each of those summations indepen-


dently.

P
Part I: T ∈H 1

This is just counting the number of elements of H, i.e. the number of subsets
n

with n/2 elements out of a larger set of size n. But we know that’s just n/2 .

24
P
Part II: T ∈H sum(T )

Expand out sum(T ) and interchange the order of summations. Let P be the
set of the first n primes.
XX XX
p= p
T ∈H p∈P p∈P T ∈H
p∈T T ∋P
X X
= p 1.
p∈P T ∈H
T ∋p

Instead of iterating over all T , then enumerating all primes p contained in


this T : we iterate over all primes p, then count the number of sets T which
contain this p. But note that “the number of T which contain some prime
p” is always the same, regardless of the actual value of p.
n−1

The answer is always n/2−1 . We include p in the subset; then, of the
remaining n − 1 primes, we need to choose the other n/2 − 1 elements of the
subset.

So, the above summation is just


X  n−1 
p
p∈P
n/2 − 1

which can be computed in linear time.

25
sum(T )2
P
Part III: T ∈H

Again, expand out the inner summation and interchange the order of sum-
mations again.
 2
X X  X XX

 p  =
 pq
T ∈H p∈P T ∈H p∈P q∈P
p∈T p∈T q∈T
XX X
= pq
p∈P q∈P T ∈H
T ∋p,q
XX X
= pq 1.
p∈P q∈P T ∈H
T ∋p,q

That is to say, consider all pairs of primes (p, q). We wish to count the
number of sets T which contain both p and q. But that’s again (mostly)
independent of p and q:

• If p = q, then the count is n/2−1


n−1

, as earlier.

• If p ̸= q, then the count is n/2−2


n−2

for basically the same reason.

All in all, we are now at this summation:


X  n−1  X  n−2 
p2 + pq .
p∈P
n/2 − 1 p,q∈P
n/2 − 2
p̸=q

Directly evaluating the summation on the right in O(n2 ) gets you Subtask 3.

Computing it in linear time (which isn’t too hard) gets you Subtask 4.
!2
X
Hint: Consider again the expression p .
p∈P

26
I) Stratosphere

Subtask 1

You can enumerate all paths using a computer program (or by hand). Or,
you can do the Subtask 2 solution by hand.

27
Subtask 2

This is a classic DP problem. Let dp(i, j) be the sum of the thrills of all
paths that start at (i, j) and end on the bottom right corner.

Construct the path step by step. From some position (i, j), ask: Do I go
down, or do I go right? Either way, the path has already passed through cell
(i, j). Then, after the move, we need to consider the sum of the thrills of all
paths from our new position.

You should get something like:

dp(i, j) = vi,j · (dp(i + 1, j) + dp(i, j + 1))

where vi,j = r − (i − 1) (assuming 1-indexing) is the value of the number at


that cell.

28
Subtasks 3 & 4

Note that each path can be uniquely identified by how many squares of our
path are in each row. For example, the path in the sample is the unique one
that passes through 1 thrice, through 2 once, and through 3 twice.

So, essentially, we want to evaluate this sum of products:


X
1i1 2i2 3i3 . . . rir

across all tuples (i1 , i2 , i3 , . . . , ir ) such that:

• 1 ≤ it ≤ c for each t;


P
it = r + c − 1.

This is some kind of convolution, and smells like a perfect place to apply
generating functions! Specifically, what we want is the coefficient of xr+c−1
in the polynomial:

(1x + (1x)2 + · · · + (1x)c )(2x + (2x)2 + · · · + (2x)c ) . . . (rx + (rx)2 + · · · + (rx)c ).

First, apply the following simplification. The above polynomial is equal to


(using product notation now):
r
Y
r
r!x ((tx)0 + (tx)1 + · · · + (tx)c−1 )
t=1

by factoring out tx from each term for t = 1 to r. But, the coefficient of


xr+c−1 in this polynomimal is equivalent to the coefficient of xc−1 in
r
Y
r! ((tx)0 + (tx)1 + · · · + (tx)c−1 )
t=1

(that is, we divided everything by xr ).

We want the coefficient of xc−1 in this polynomial. That means even if we

29
introduce extra terms in the polynomial, the answer won’t change, as long
as all terms have degree c or higher. So, we can equivalently consider:
r
Y
r! ((tx)0 + (tx)1 + · · · + (tx)c−1 + (tx)c + (tx)c+1 + . . . )
t=1

Our finite geometric series becomes an infinite one, which has a nicer formula!
r
Y 1
r! .
t=1
1 − tx

At this point, you may recognize this as one of the generating functions of
the Stirling numbers of the second kind! Then, you can go to Wikipedia and
find an explicit formula that can be computed in O(r). But if not, we can
proceed—these next steps essentially provide a proof of that explicit formula.

From here, we can do familiar partial fraction decomposition. There exist


coefficients k1 , k2 , . . . , kr such that
r r
Y 1 X kt
r! = r! .
t=1
1 − tx t=1
1 − tx

From standard partial fractions techniques, we know that we can compute


each kt using the following relation:
Y
kt (1 − q/t) = 1.
q̸=t

Then, the coefficient of xc−1 overall can be computed as the sum of the
coefficient of xc−1 in each individual summand. But each individual summand
is an infinite geometric series, so it contributes kt · tc−1 to the sum.

If you compute the kt directly in quadratic time, you get Subtask 3.

To get Subtask 4, you have to compute them more smartly, which can be
done by noticing shared computations between each kt (instead of starting
over from scratch every time).

30
J) Roll the Dice

Subtasks 1 & 2

Just code it.

Note that for Subtask 2, cubic time solutions won’t pass. You can afford to
iterate over all subarrays, but you cannot afford to literally compute each
subarray’s value from scratch.

Fortunately, it’s not too hard to fix, and rather intuitively too—the result
of applying commands ℓ through r can be found by: taking the results from
applying commands ℓ through r − 1, and then applying command r.

So, each of the O(n2 ) subarrays can be processed in O(1) time only.

31
Subtask 3

We’re pretty much going to do DP.

Let dpr (x) count the number of subarrays whose right endpoint is r, and
which result in face x facing upwards. Let y be the face such that: if face y
is on top, then performing a right hand twist around face ar results in face
x now being on top.

We see that if we want actions ℓ through r to land on face x, then it must


be the case that actions ℓ through r − 1 land on face y (and then action r
makes it land on face x).

dpr (x) = dpr−1 (y) + (1 if y = 1, else 0),

Here, the (1 if y = 1, else 0) term corresponds to the fact that we can start a
new subarray here whose left endpoint is r (but as per the problem statement,
a fresh die always start with 1 facing up).

We can evaluate all of dpr (x) from r = 1 to n and x = 1 to 6 in linear time.

32
Subtask 4

Note that the sequence b (and thus also the sequence a) is periodic, with
period 218 . To solve the problem for n = 1018 , we just abuse this periodicity
with standard period-bashing techniques, since the same 218 actions will be
repeated over and over again.

We have six linear recurrence relations that evolve in lockstep with each
other. Thus, we can encode each possible transition as one of six possible
matrices (one for each possible value of ai , i.e. which face we’re twisting
around).

Let A be the matrix that we get by multiplying the corresponding matrices


of commands 1 through 218 , in order. Then, applying the transition en-
coded by A over and over and over again can be represent by fast matrix
exponentiation—we raise A to the power of 1018 /218 .

In order to get the sum of these values for all r from 1 to n, we have a few
options:

• Augment the matrices so that we also keep track of the running sum
for each face.

• Use the geometric series formula

• Use divide and conquer

Any of these should work.

33

You might also like