ACM ICPC World Finals 2011
First we note that the number of multiplications used in any solution must be small: there can be at most 29 of them (since if m > 1 using more multiplications inevitably gives us numbers larger than 109, and if m = 1 multiplications are useless). So we’ll try all possible values g for the number of multiplication operations used by the solution.
Next, given the value of g we’ll have to figure out how to do the additions. For 0 ≤ i ≤ g, let us denote by hi the number of additions performed between the i’th and (i + 1)’th multiplication operations. So for example h0 is the number of additions performed before the first multiplication and hg is the number of additions after the last one. Then, the resulting program transforms input x to α(x) = x·mg + a·∑i=0g hi·mg−i. The constraint that the input range [p, q] is mapped to [r, s] is then equivalent with requiring that ∑i=0g hi·mi lies in the interval [(r − p·mg)/a, (s − q·mg)/a]. Let us denote this new interval by [u, v]. If [u, v] contains no integers, it will be impossible to choose valid hi’s (for this choice of g). Otherwise, there is a solution.
To minimize the total number of operations, i.e., the sum of the hi’s (plus g, which is fixed at this point) we can choose the hi’s in a greedy fashion: starting from hg working our way down to h0, try to choose hi to be as large as possible without having ∑i=0g hi·mi exceeding v, with the exception that once the sum goes beyond u we should stop.
What remains is to be able to compare solutions to pick the lexicographically smallest shortest one, we’ll leave this to the reader.