CUC-SUMMER-2-E

E - Catch That Cow
POJ - 3278

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.


题意:JOHN要抓住他的牛,有两种移动方式,坐标加一或减一,坐标翻倍,牛不会动,求最少移动几次。

解法:宽搜,递归,开一个和范围一样大的数组来记录坐标是否到达过,从起始点进行三种移动,将移动后坐标标记并加到队列中,如果移动后坐标已经被标记了则返回,这说明一定可以用更少的移动到达这一点。

代码:

#include<iostream>
#include<queue>
using namespace std;
int ans=0;
int a[100100]={0,};
int n,k;
struct point{
    int x,step;
};
queue <point> q;
point start;
int BFS()
{
    while(!q.empty()){
        point now;
        now=q.front();
        q.pop();
        if(now.x==k){
            n=k;
            ans=now.step;
            return ans;
        }
        for(int i=0;i<3;i++){
            point next;
            if(i==0)
                next.x=now.x+1;
            else if(i==1)
                next.x=now.x-1;
            else
                next.x=now.x*2;
            next.step=now.step+1;
            if(next.x>=0&&next.x<100100&&a[next.x]==0){
                a[next.x]=1;
                q.push(next);
            }
        }
    }
    return ans;
}
int main()
{
    cin>>n>>k;
    start.x=n;
    start.step=0;
    q.push(start);
    a[n]=1;
    cout<<BFS()<<endl;
    return 0;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容