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 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: N and K Output Line 1: The least amount of time, in minutes, it takes for Farmer John to catch the fugitive cow. Sample Input Sample Output Hint The fastest way for Farmer John to reach the fugitive cow is to move along the following path: 5-10-9-18-17, which takes 4 minutes. Source |
[Submit] [Go Back] [Status] [Discuss]
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;
class point {
int x;
int step;
public point(int x, int step) {
super();
this.x = x;
this.step = step;
}
public point() {
super();
step = 0;
}
}
public class Main{
static int n, k;
static int re = 0;
static int dir[] = { -1, 1, 0, 0 };
static int vis[] = new int[9000000];
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
n = cin.nextInt();// 人只往右2*x
k = cin.nextInt();// 牛
for (int i = 0; i <= n; i++)
vis[i] = 0;
if (k <= n) {
re = n - k;
} else {
point p = new point(n, 0);
bfs(p);
}
System.out.println(re);
}
private static void bfs(point x) {
// TODO Auto-generated method stub
Queue<point> queue = new LinkedList<point>();
point x1 = new point(), x2 = new point();
queue.add(x);
while (!queue.isEmpty()) {
//
x1 = queue.peek();
//System.out.println(x1.x);
//System.out.println(x1.x+"ddddddd");
queue.poll();
for (int i = 0; i < 3; i++) {
x2.x = x1.x + dir[i];
//System.out.println(dir[i]+"rrrrrrrrrrrr");
//System.out.println(x2.x+"ddddddd");
if(i==2)
{
x2.x=x1.x*2;
}
if (x2.x >= 0 && x2.x <= 1000000 && vis[x2.x] == 0) {
vis[x2.x] = 1;
x2.step = x1.step + 1;
if (x2.x == k) {
re = x2.step;
//System.out.println("cccc");
return;
} else {
//System.out.println(x2.x+"rrrrrrrrrr");
point kk=new point(x2.x,x2.step);
queue.add(kk);
//System.out.println(x2.x+"rrrrrrrrrr1111");
}
}
}
}
}
}