B - Catch That Cow
Description
Farmer John has been informed of the location of a fugitive cow and wants to catch her immediately. He starts at a point N (0 ≤ N ≤ 100,000) on a number line and the cow is at a point K (0 ≤ K ≤ 100,000) on the same number line. Farmer John has two modes of transportation: walking and teleporting.
* Walking: FJ can move from any point X to the points X - 1 or X + 1 in a single minute
* Teleporting: FJ can move from any point X to the point 2 × X in a single minute.
If the cow, unaware of its pursuit, does not move at all, how long does it take for Farmer John to retrieve it?
Input
Output
Sample Input
5 17
Sample Output
4
Hint
1 import java.io.BufferedInputStream; 2 3 import java.util.Arrays; 4 5 import java.util.Scanner; 6 7 public class Main { 8 public static void main(String[] args) { 9 Scanner s = new Scanner(new BufferedInputStream(System.in)); 10 while (s.hasNext()) { 11 int a = s.nextInt(), b = s.nextInt(); 12 int[] l = new int[100010]; 13 int starts = 0; 14 int ends = 0; 15 l[0] = a; 16 int n[] = new int[100010]; 17 Arrays.fill(n, 0); 18 while (true) { 19 int v = l[starts]; 20 if (v == b) 21 break; 22 if (n[v+ 1] == 0 && v + 1 <= 100000) { 23 l[++ends] = v + 1; 24 n[v + 1] = n[v] + 1; 25 } 26 if (v - 1 >= 0 && n[v - 1] == 0) { 27 l[++ends] = v - 1; 28 n[v - 1] = n[v] + 1; 29 } 30 if (v * 2 <= 100000 && n[v * 2] == 0) { 31 l[++ends] = v * 2; 32 n[v * 2] = n[v] + 1; 33 } 34 starts++; 35 } 36 System.out.println(n[b]); 37 } 38 s.close(); 39 } 40 }