zoukankan      html  css  js  c++  java
  • poj 3278 bfs

    Catch That Cow
    Time Limit: 2000MS   Memory Limit: 65536K
    Total Submissions: 41703   Accepted: 13005

    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

    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.

    Source

     
    练习怎用队列
    import java.awt.Point;
    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    
    class Bfs{
    	private static final int SIZE=200000;
    	private int s, t;
    	private boolean[] vis;
    	private Queue<Point> q;
    	public Bfs(int s, int t){
    		this.s=s; this.t=t;
    		q = new LinkedList<Point>();
    		vis = new boolean[SIZE];
    		for(int i=0; i<SIZE; i++) vis[i]=false;
    	}
    	
    	public int run(){
    		q.add(new Point(s,0));
    		while(!q.isEmpty()){
    			Point cur = q.poll();
    			if(cur.x == t) return cur.y;
    			int y = cur.y+1;
    			if(cur.x>0 && !vis[cur.x-1]){
    				q.add(new Point(cur.x-1,y));
    				vis[cur.x-1]=true;
    			}
    			if((cur.x<<1)<SIZE && !vis[cur.x<<1]){
    				q.add(new Point(cur.x<<1,y));
    				vis[cur.x<<1]=true;
    			}
    			if(cur.x+1<SIZE && !vis[cur.x+1]){
    				q.add(new Point(cur.x+1, y));
    				vis[cur.x+1]=true;
    			}
    		}
    		return SIZE>>1;
    	}
    }
    
    public class Main {
    	static final int INF = 200000;
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner s = new Scanner(System.in);
    		while(s.hasNext()){
    			int n = s.nextInt(), k=s.nextInt();
    			Bfs bfs = new Bfs(n,k);
    			System.out.println(bfs.run());
    		}
    	}
    }
    
  • 相关阅读:
    python之virtualenv
    Markdown学习
    Python之进程(multiprocessing)
    python之concurrent.futures模块
    Python之线程
    LoadRunner(四)、检查点
    LoadRunner(三)、关联
    LoadRunner(二)、录制
    LoadRunner(一)、安装
    Jmeter(十九)逻辑控制器之if控制器
  • 原文地址:https://www.cnblogs.com/ramanujan/p/3582822.html
Copyright © 2011-2022 走看看