Editorial for DMOPC '19 Contest 7 P4 - Bob and Continued Fractions


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.

Author: Kirito

The key observation for this problem is that given the fraction ab in lowest terms, k+1ab will also be in lowest terms.

The proof is as follows. Simplifying the expression yields k+ba=ka+ba. Let us consider gcd(ka+b,a). By the Euclidean algorithm, we know this equals gcd(b,a), and as ab is in lowest terms, gcd(ka+b,a)=gcd(b,a)=1. QED

Thus if we represent the fraction ab as the matrix [ab], we can express k+1ab as the matrix [k110][ab].

For 10% of points, we can answer each query by multiplying together the corresponding matrices.

Time Complexity: O(NQ)

For the remaining 90% of points, we can use a range tree and the associative property of matrix multiplication to obtain a solution in O(QlogN).

Alternatively, we can use a technique similar to the idea of prefix sum arrays. Note that [k110]1=[011k]. We can precompute i=1k[ai110] and i=1k[011ai] for k=1,2,,N in O(N), thus the product i=lr1[ai110] can be found in O(1).

Time Complexity: O(N+Q)

A final solution is as follows. We claim that for any continued fraction a1+1a2+1+1ak+1x there exists a,b,c,d such that a1+1a2+1+1ak+1x=ax+bcx+d.

This is equivalent to the matrix solution, and the proof of correctness is left as an exercise for the reader.


Comments

There are no comments at the moment.