Catch that Cow
Time Limit: 2000MS |
|
Memory Limit: 65536K |
Total Submissions: 71439 |
|
Accepted: 22496 |
Description
Farmer John had 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 are at a point K (0≤ K ≤100,000) on the same number line. Farmer John has 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 2x 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
Line 1:two space-separated integers:
Nand
K
Output
Line 1:the least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow.
Sample Input
5 17
Sample Output
4
Hint
The fastest-Farmer John to reach the fugitive cow are to move along the following PATH:5-10-9-18-17, which takes 4 Minutes.
Re several times, the max value is changed to more than 200,000 AC. However, the running time is more than 2000 MS, it feels Java is really much slower than C + +.
Java AC Code
Importjava.util.LinkedList;ImportJava.util.Queue;ImportJava.util.Scanner; Public classMain {Staticqueue<integer> queue =NewLinkedlist<integer>(); Static intmax = 200010; Static BooleanMarked[] =New Boolean[Max]; Static intSteps[] =New int[Max]; Static intBoy , Cow; Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); Boy=Sc.nextint (); Cow=Sc.nextint (); BFS (); System.out.println (Steps[cow]); } Public Static voidBFs () {queue.add (boy); Steps[boy]= 0; Marked[boy]=true; while(!Queue.isempty ()) { intHead =Queue.poll (); if(head-1 >= 0 &&!marked[head-1]) {Steps[head-1] = Steps[head] + 1; Marked[head-1] =true; Queue.add (Head+ W); } if(head + 1 < max &&!marked[head + 1]) {Steps[head+ 1] = Steps[head] + 1; Marked[head+ 1] =true; Queue.add (Head+ 1); } if(Head * 2 < Max &&!marked[head * 2]) {Steps[head* 2] = Steps[head] + 1; Marked[head* 2] =true; Queue.add (Head* 2); } if(Marked[cow])return; } } }
POJ 3278 Catch that Cow