poj 3278 Catch That Cow
Posted kk_kk
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3278 Catch That Cow相关的知识,希望对你有一定的参考价值。
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 71439 | Accepted: 22496 |
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
RE了好多次,把max值改为20多万就AC了。 然而运行时间还是2000多MS,感觉Java真的比C++要慢好多。。
Java AC 代码
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static Queue<Integer> queue = new LinkedList<Integer>(); static int max = 200010; static boolean marked[] = new boolean[max]; static int steps[] = new int[max]; static int boy, cow; public static void main(String[] args) { Scanner sc = new Scanner(System.in); boy = sc.nextInt(); cow = sc.nextInt(); bfs(); System.out.println(steps[cow]); } public static void bfs() { queue.add(boy); steps[boy] = 0; marked[boy] = true; while(!queue.isEmpty()) { int head = queue.poll(); if(head - 1 >= 0 && !marked[head - 1]) { steps[head - 1] = steps[head] + 1; marked[head - 1] = true; queue.add(head - 1); } 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的主要内容,如果未能解决你的问题,请参考以下文章
POJ 3278 - Catch That Cow - [BFS]