zoukankan      html  css  js  c++  java
  • POJ 3278 BFS

    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.
     
    tips:广搜入门题目。感觉广搜比深搜容易理解一点,因为不用递归,递归太过于抽象,也难debug。
      数轴上,要从n到k去,每次三种变换坐标的方法(n+1,n-1,n*2)
      用队列储存n,然后出队n,进队三个新坐标,如此循环,每次进队都要判断新坐标和k是否相等,不相等就step[next] = step[head] + 1;相等则return step[next]。
     
    #include <bits/stdc++.h>
    using namespace std;
    #define maxn 100001
    queue<int>q;
    int step[maxn];
    int vis[maxn];
    
    int bfs(int n, int k){
    	int head,next;
    	q.push(n);//进队
    	step[n] = 0;//步数初值为0
    	vis[n] = 1;//标记这个点已经走过了
    	while(!q.empty()){
    		head = q.front();//把队首(n)的值赋给head,这一步必须放在循环外面。不然三个坐标会尝试三次。
    		q.pop();//出队 
    		for(int i = 0; i < 3; i++){
    			if(i == 0) next = head-1;
    			else if(i == 1) next = head+1;
    			else  next = 2*head;//三个新坐标
    			if(next > maxn || next < 0) continue;//考虑越界
    			if(!vis[next]){
    				q.push(next);//next进队
    				step[next] = step[head] + 1;//步数+1,ps,这里用的step[head]+1,在每次循环的时候,他的初始值是一样的。
    				vis[next] = 1;//标记为旧点
    			} 
    		if(k == next) return step[next];
    	}	
    }
    }
    
    int main(){
    	int n,k;
    	cin>>n>>k;
    	memset(vis,0,sizeof(vis));
    	memset(step,0,sizeof(step));
    	while(!q.empty()) q.pop();
    	if(n>k) cout<<n-k<<endl;
    	else cout<<bfs(n,k)<<endl;
    	return 0;
    }
    
  • 相关阅读:
    在VMWare的虚拟机中设置共享文件夹(Linux-Ubuntu系统)
    得到cell视图
    推送
    常用框架
    截屏
    多线程枷锁
    java与IOS的交互
    缓存机制
    iOS数据库操作(使用FMDB)
    插入排序
  • 原文地址:https://www.cnblogs.com/stul/p/9991217.html
Copyright © 2011-2022 走看看