您的位置:首页 > 编程语言 > Java开发

POJ 3278 Catch That Cow (Java,bfs)

2018-02-22 00:44 543 查看
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

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

5 17

Sample Output

4

farmer john是何方神圣….今天养牛明天锯木头,看起来日子不错,不过为什么总是要我帮忙解决问题???

总觉得这个宽搜跟暴力枚举差不多…可能没有剪枝的搜索算法其实本质都是暴力吧….

这次他遇到的问题是牛丢了需要找牛(上次他的牛怎么了来着?要排队回仓库还是怎么着…),超时空农夫john在寻找傻牛(牛不会动)的时候可以选择向前走、向后走和时空跃迁(坐标乘2),每种走法费时一分钟,问最少需要几分钟。

解题思路是宽搜,枚举可能的走法去搜索出一条最短路径,建一个step数组存步数。

AC代码:

public class Main {

public static void main(String[] args) {
// Scanner reader = new Scanner(System.in);
InputReader reader = new InputReader();
int n = reader.nextInt();
int k = reader.nextInt();
if (n >= k) {// 已经在牛那儿了或者超过牛了,特判一下
System.out.println(n - k);
return;
}
final int MAX_N = 1000000;// 规避魔法值...今天心情好
int[] step = new int[MAX_N + 5];
boolean[] visited = new boolean[MAX_N + 5];
// 宽搜部分↓
Queue<Integer> wait = new LinkedList<Integer>();
wait.add(n);// 搜索起始点
visited
= true;// 手动标记起始点已被访问
int cur = 0;
int next = 0;
while (!wait.isEmpty()) {
cur = wait.poll();
for (int i = 0; i < 3; i++) {
switch (i) {// 用switch实现三种走法,对连续if else有阴影,能不用就不用
case 0:
next = cur + 1;
break;
case 1:
next = cur - 1;
break;
case 2:
next = cur * 2;
default:
break;
}
if (next >= 0 && next <= MAX_N) {
if (!visited[next]) {
step[next] = step[cur] + 1;
wait.add(next);
visited[next] = true;
}
if (next == k) {
System.out.println(step[next]);
return;
}
}
}
}
}
}


最后好多括号…..这可能就是遵循阿里巴巴Java开发规范(无论代码是不是只有一条,必须带大括号)的弊病吧…..

说起这个规约,顺带一提,这个插件管的还真是宽:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: