Ninja has a robot that can move in an infinite number line. The robot starts at position 0, with speed = +1. The robot moves automatically according to the sequence of instructions “A” (Accelerate) and “R” (Reverse).
When robot get an instruction "A", the robot does the following: position += speed, speed *= 2.
When the robot gets an instruction “R”, the robot does the following: if its speed is positive then speed = -1, otherwise speed = +1. The position of the robot will remain the same.
For example, after commands "AAARA", the robot goes to positions 0->1->3->7->7->6, and robot speed goes to 1->2->4->8->-1->-2.
You are given a positive integer ‘TARGET’, and your task is to find and return the length of the shortest sequence of instruction to reach position equals ‘TARGET’.
Note :
The position of the robot can be negative.
Input Format :
The first line contains a single integer ‘T’ representing the number of test cases. The 'T' test cases follow.
The first line of each test case will contain a single integer ‘TARGET’.
Output Format :
For each test case, print an integer representing the length of the shortest sequence of instruction to reach position equals ‘TARGET’.
Output for every test case will be printed in a separate line.
Note :
You don’t need to print anything, It has already been taken care of. Just implement the given function.
Constraints :
1 <= 'T' <= 50
1 <= ‘TARGET’ <= 10000
Time limit: 1 sec
2
1
2
1
4
In the first test case, The shortest sequence of instruction is ‘A’.
In the second test case, The shortest sequence of instruction is ‘AARA’, and the position changes as 0->1->3->3->2.
2
6
7
5
3
Track all the possible positions of the robot after each instruction.
The basic idea is to use modified Breadth-First Search (BFS) here. We can keep track of all the possible positions of the robot after ‘N’ instructions (N = 0, 1, 2, 3, 4, ...) and return the smallest ‘N’ such that the ‘TARGET’ position is reached
The steps are as follows:
O(2^N), where 'N' is the maximum number of instructions.
In each step we have two choices ‘R’ or ‘A’, Thus overall there are 2^N choices for ‘N’ instructions. Thus overall complexity will be O(2^N),
O(2^N), where 'N' is the maximum number of instructions.
The space used by the queue will be O(2^N).