hdu 2717 Catch That Cow

本文介绍了一个有趣的算法问题:一位农夫需要在最短时间内找到并抓回一只逃逸的奶牛。通过使用两种不同的移动方式——步行与瞬移,农夫可以在数轴上快速接近目标。文章提供了一段实现此问题解决方案的C++代码,并通过广度优先搜索(BFS)算法找到了最优路径。
Problem 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.

简单广搜,坑爹的注意起点等于终点就行了;

#include<map>
#include<set>
#include<cmath>
#include<queue>
#include<bitset>
#include<math.h>
#include<vector>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iostream>
#include<algorithm>
#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;

struct node{
  int x,step;
}s,e,q,p;
int dir[8][2]={{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1},{-2,1},{-1,2}};
int next1[2]={1,-1};
int vis[1000005];
bool judge(node a){
    if(a.x<0||a.x>1000000||vis[a.x]) return false;
    return true;
}
int bfs(){
    queue<node>que;
    s.step=0;
    vis[s.x]=1;
    que.push(s);int s=1;
    while(!que.empty()){
        q=que.front();//printf("%d->%d\n",q.x,q.step);
        que.pop();

        for(int i=0;i<2;i++){
            p=q;
            p.x=q.x+next1[i];
            if(judge(p)){
                vis[p.x]=1;
                p.step++;
                que.push(p);//printf("%d %d %d %d\n",p.x,p.y,e.x,e.y);
                if(p.x==e.x)
                return p.step;
            }
        }
        p=q;
        p.x=q.x*2;//printf("%d~~\n",p.x);
        if(judge(p)){
            vis[p.x]=1;
            p.step++;
            que.push(p);
            if(p.x==e.x)
               return p.step;
        }
    }
}
int main(){
    int a,b;
    while(~scanf("%d%d",&a,&b)){
         memset(vis,0,sizeof(vis));
         s.x=a,e.x=b;
         if(s.x==e.x)printf("0\n");
         else
             printf("%d\n",bfs());
    }
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值