poj 3278 Catch That Cow

来源:互联网 发布:广州seo顾问 编辑:程序博客网 时间:2024/06/14 17:08
package bfs;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**问题请参考http://poj.org/problem?id=3278
 * @author rayli

 * @date:2014-7-18 上午8:53:05
 * 题意: 有一个农民和一头牛,他们在一个数轴上,牛在k位置保持不动,农户开始时在n位置。
 * 设农户当前在M位置,每次移动时有三种选择:1.移动到M-1;2.移动到M+1位置;3.移动到M*2的位置。
 * 问最少移动多少次可以移动到牛所在的位置。所以可以用广搜来搜索这三个状态,直到搜索到牛所在的位置。
 *
 */
public class CatchCow
{   
    static int ans;
    boolean vist[] = new boolean[100005];
    
    boolean judge(int n)
    {
        if(n >= 0 && n <= 100000)
            return true;
        
        return false;
    }
    void BFS(int n, int k)
    {
        if(n == k)
            return;

        Queue<Integer> q = new LinkedList<Integer>();
        
        vist[n] = true;
        q.add(n);
        
        while(!q.isEmpty())
        {
            int t = q.size();
            ans++;
            
            while(t-->0)
            {
                int tmp = q.poll();
                
                if(tmp == k)
                    return;
                
                for(int i=0; i<3; i++)
                {   
                    int tt = tmp;
                    if(i == 0)
                        tt -= 1;
                    else if(i == 1)
                        tt += 1;
                    else if(i == 2)
                        tt *= 2;
                    
                    if(tt == k)
                        return;
                    else if(judge(tt) && !vist[tt])
                    {
                        vist[tt] = true;
                        q.add(tt);
                    }
                }
            }
        }
    }
    
    public static void main(String args[])
    {
        Scanner cin = new Scanner(System.in);
        
        int N = cin.nextInt();
        int K = cin.nextInt();
        ans = 0;
        
        CatchCow cc = new CatchCow();
        cc.BFS(N, K);
        
        System.out.println(ans);
        cin.close();
    }
}