zoukankan      html  css  js  c++  java
  • [ACM] hdu 2717 Catch That Cow (BFS)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2717

    参考链接:http://blog.csdn.net/sr_19930829/article/details/26398223

    import java.util.LinkedList;
    import java.util.Queue;
    import java.util.Scanner;
    
    
    public class Main {
    	
    	static int N,K;
    	static int len=100000;
    	static int[] hash = new int[len+10];
    	static boolean[] vis = new boolean[len+10];
    	
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc = new Scanner(System.in);
    		N = sc.nextInt();
    		K = sc.nextInt();
    		if(N==K){
    			System.out.println(0);
    		}else
    		{
    			bfs();
    			System.out.println(hash[K]);
    		}
    
    	}
    
    	private static void bfs() {
    		// TODO Auto-generated method stub
    			Queue<node> queue = new LinkedList<node>();
    			node n = new node(N);
    			queue.offer(n);
    			vis[N] = true;
    			hash[N] = 0;
    			while(!queue.isEmpty()){
    				node temp = queue.poll(); //queue.poll() 获取并移除队头
    				int num = temp.getNum();
    				if(num+1==K||num-1==K||num*2==K){//找到
    					hash[K]=hash[num]+1;
    					break;
    				}
    				if(num-1>=0&&!vis[num-1]){
    					node m = new node(num-1);
    					queue.offer(m);
    					vis[num-1]=true;
    					hash[num-1]=hash[num]+1;
    				}
    				if(num+1<=len&&!vis[num+1]){
    					node m = new node(num+1);
    					queue.offer(m);
    					vis[num+1] = true;
    					hash[num+1] = hash[num]+1;
    				}
    				if(num*2<=len&&!vis[num*2]){
    					node m = new node(num*2);
    					queue.offer(m);
    					vis[num*2]=true;
    					hash[num*2]=hash[num]+1;
    				}
    			}
    			
    			
    		
    		
    		
    	}
    	
    	public  static class node{
    		int num;
    		public node(int num){
    			this.num = num;
    		}
    		public int getNum() {
    			return num;
    		}
    		public void setNum(int num) {
    			this.num = num;
    		}
    		
    	}
    
    	
    }
    

      没有AC不知道为什么。

  • 相关阅读:
    然乌湖
    邦达 八宿
    芒康
    巴塘
    禾尼乡 所波大叔
    世界高城 理塘
    相克宗 藏民家
    骑行川藏--新都桥&塔公草原
    d 3
    D2
  • 原文地址:https://www.cnblogs.com/fjl-vxee/p/6402011.html
Copyright © 2011-2022 走看看