poj 3278 Catch That Cow

Posted kk_kk

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj 3278 Catch That Cow相关的知识,希望对你有一定的参考价值。

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 - 1 or + 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

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.

 

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

POJ 3278 - Catch That Cow - [BFS]

POJ 3278 Catch That Cow(模板——BFS)

poj3278Catch That Cow

POJ 3278: Catch That Cow

poj3278 Catch That Cow