You are given four integers a,b,c,d where 1 ≤ a,b,c,d ≤ 1000. Consider (a,b) as a pair. By using zero or more steps is it possible to get (c,d)?
From (x,y) you can either jump to (x+y,y) or (x,x+y) which is a single step.
Idea 1:
By applying BFS with queue you can solve this. Each state in queue is a pair of integers. Initial state is (a,b) that is given in the input. If anytime you can reach (c,d) which is given in the input, return “Able to generate”. Otherwise “Not able to generate”. rumman_sust has solved this problem in this way here.
Idea 2:
If we start from (c,d) and try to go back to (a,b) size of code becomes smaller with some intuition.
In pair (x,y) both x,y are positive according to input. From (x,y) if you jump to (x+y,y) then x+y will never be equal to y. Again From (x,y) if you jump to (x,x+y) then x+y will never be equal to x. So you can handle the trivial cases in the following way:
if(a == c && b ==d)
return "Able to generate";
if(c == d)
return "Not able to generate";
from pair (c,d) if we go downward one step and get (x,y)
(x,y) = (c-d, d) if c>d
(x,y) = (c,d-c) if d>c
from (x,y) we will start the above process again. If anytime we reach (a,b) that is given in the input we are done. Otherwise Impossible.
Final code:
class PairGameEasy {
public:
string able(int a, int b, int c, int d)
{
if(a == c && b ==d)
return "Able to generate";
if(c == d)
return "Not able to generate";
while(c > 0 && d > 0)
{
if(a == c && b ==d)
return "Able to generate";
if(c > d)
c -= d;
else
d -= c;
}
return "Not able to generate";
}
Idea 3:
This problem can also be solved by dp by keeping a 2D array.
naseef_cuet has solved this problem in this way which is quite easy to understand.
int A[1011][1011];
class PairGameEasy {
public:
string able(int a, int b, int c, int d) {
for(int i=0;i<=1000;i++)
{
for(int j=0;j<=1000;j++)
{
A[i][j]=0;
}
}
A[a][b]=1;
for(int i=0;i<=1000;i++)
{
for(int j=0;j<=1000;j++)
{
if(A[i][j]==1)
{
if(i+j<=1000)
{
A[i+j][j]=1;
A[i][i+j]=1;
}
}
}
}
if(A[c][d]==1)
return "Able to generate";
else return "Not able to generate";
}
};
My long boring code during contest is here.