PROBLEM LINK:
Author: Vitalij Kozhukhivskij
Tester: Shang Jingbo and Gerald Agapov
Editorialist: Devendra Agarwal
DIFFICULTY:
SIMPLE
PREREQUISITES:
Maths.
PROBLEM:
You need to reach point (x,y) from (0,0) using snake game rule only difference is that snake cannot travel straight for more than 1 unit and the first step is in the Y-axis.
Explanation
As the snake move is totally symmetrical , we can assume that number of steps required to reach from (0,0) to (x,y) is independent of the sign of x and y.
Reason
First move is in either positive Y or negative Y axis. From there , snake can either move in negative or positive x axis and so on.
Case 1: Let us solve the case when y = 0, i.e steps required to reach (x,0) from (0,0):
Wlog we can assume that x is positive . Now if x is odd , then total number of 2x+1 steps are required.
Proof is immediate by sketching a small diagram [ Remember that the first move is towards Y axis ] . If x is even , then total number of steps required is 2x , proof by sketching.
Case 2: Let us solve the case when x = 0, i.e steps required to reach (0,y) from (0,0):
Wlog we can assume that y is positive . Now if y is odd , then total number of 2y-1 steps are required . If y is even , then total number of 2y steps are required.
Case 3: Let us now solve the case when neither x nor y are zero :
Till now , you must have realized that the snake move is perpendicular and it will cover 1 unit in y and 1 unit in x direction . So first move to (min(x,y) , min(x,y) ) and cover the remaining distance by the above cases discussed.
Pseudo Code
get_answer(x,y):
x= abs(x); //get the absolute value of x
y=abs(y); //get the absolute value of y
z=min(x,y); //get the minimum of x and y
return 2*z + val(x-z,y-z))
// if a is 0 , then it is case 2 , else it is case 1.
val (a , b) : //either case 1 or case 2
return ( (a&1) ? (2*a+1) : (2*a) ) + ( (b&1) ? (2*b-1) : (2*b) );
Complexity:
O(1).