124A - The number of positions

Enumerate all the integers *i* and find out those that satisfy both *i* - 1 ≥ *a* and *n* - *i* ≤ *b*.

Generate all the feasible permutation patterns and find out the one under which the difference between the maximum number and the minimum integer is the smallest.

We divide the positions into the following sets. *A*_{2} = (2, 4, 6, ..., 2*m*_{1}), *A*_{3} = (3, 6, 9, ..., 3*m*_{2}), *A*_{5} = (5, 10, 15, ..., 5*m*_{3}),...

One can see that for any prime integer *p* > 2, *A*_{p} always has at least one common position with *A*_{2}, as long as the index 2*p* does not exceed the range. Thus, we find out the maximum such prime integer *p*', and then count the total number of different positions belonging to sets *A*_{2}, *A*_{3}, ...*A*_{p'}. These positions must have the same letters, while the other positions can have any letter. Therefore, the left work is to determine whether we have enough number of the same letter.

We first focus on the first condition and consider *y* = 0. One can see that the bad points are distributed on the X-axis with distance 2*a*. After increasing *y* to 1, 2, ... + ∞ , one can find that the bad points form multiple lines with - 45 degrees. Similarly, the second condition results in multiple lines with + 45 degrees.

As a result, the bad points have divided the whole plane into infinite grids. To get from the starting point to the ending point, we have to cross several (maybe zero) grids. The answer is just the least number of grids that we have to cross. In fact, this is quite similar to the Manhattan Distance. We consider the lines with + 45 and - 45 degrees as the “X” and “Y” axis, respectively. Then, we can calculate the manhattan distances of the two points, along the “X” and “Y” axis, as *D*_{x} and *D*_{y}. The answer is *max*(*D*_{x}, *D*_{y}).

I read the tutorials and I think the ideas behind this problem is really very amazing. It needs quite strong insight to reduce the problem to single dimension, which is not that straightforward, at least for me. I think I should work harder to improve my insight.