UVa 10120 - Gift?!

UVa 10120 - Gift?!

 * http://acm.uva.es/p/v101/10120.html

Summary
A river is laid out with rocks (R) as follows:
 * [left bank] R[1] R[2] R[3] R[4] ... R[N] [right bank]
 * The distance between [left bank] and R[1], R[N] and [right bank], R[i] and R[i+1] (1<=i<N), are all exactly 1 meter.
 * A frog, Frank, is trying to reach R[M] starting from the left bank, such that:
 * The first jump he mades jumps from the [left bank] onto R[1],
 * Each subsequent jump he must jump over 2*i-1 meters (2*i rocks, or going from R[k] to R[k+2*i-1] or R[k-(2*i-1)].
 * He cannot reach [left bank] or [righr bank] at any time after his first jump.

Is it possible for Frank it reach R[M]?

Explanation
You can do this with simulation for small number of N (In this problem 2<=N<=10^6, 2<=M<=N). If N is small (N<=100), we can apply the following induction:

At each step, we have a set of locations that Frank can reach.


 * At step 1, Frank can reach {1}.
 * For each location x Frank can reach at step i, Frank can reach x+(2*(i+1)-1) and x-(2*(i+1)-1) at step (i+1). Simplify: x+2*i+1 or x-2*i-1, provided that 1<=x<=N.


 * Thus, we'll have an array of sets telling us precisely at each step the locations that Frank can be on. If M appears in any of those sets, then it means that at some step i, Frank can be on R[M] (it is possible).


 * Note that for a set on step i>1 to be non-empty, the set on step (i-1) must be non-empty. Since at one point of the simulation, Frank will be getting "out of bounce" no matter how he jumps (he jumps too far to be remained on some rock), and thus the simulation can terminate since no more rocks will be reachable from that point on.


 * For bigger N, the simulation will get TLE. We should next prove that for N>=49, any problem instance P(N,M) (49<=N, M<=N) should return true.

Prove Tautological Property for N>=49
Proof:

(1)First, we will propose a strategy to achieve P(N,M) in general:

(1.1) For $$M = k^2$$ for positive integer k, there's always a solution:

Note that, 1+3+5+7+...+ (2k-1) = k^2. Thus, Frank simply keep jumping forward.

(1.2) If at any time Frank is at R[x], and the next jump is (2k+1) meters for some k, then:

If x-(2k+1)>=1, then Frank can arrive at R[x+2] (for x+2<=M):

Proof 1.2:

Assume Frank is at R[x] and the next jump is (2k+1). Furthermore, assume that x-(2k+1)>=1: Frank cam jump to the left, arriving at (x-(2k+1)) and then right, arriving at (x-(2k+1)+(2k+3)) = (x+2). That is, Frank can jump left to arrive at some rock (x-(2k+1)), then jump right to arrive at R[x+2]. Since (x-(2k+1))>=1, and x+2<=N, Frank's moves are valid.

(1.3)

Gotchas

 * N/A

Implementations
Notes/Hints on actual implementation here.

Optimizations
Optimizations here.

Input
Input Here

Output
Output Here