HDU 2717 Catch That Cow(常规bfs)

传送门:http://acm.hdu.edu.cn/showproblem.php?pid=2717

 

Catch That Cow

Time Limit: 5000/2000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 20259    Accepted Submission(s): 5926


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.
 

 

Source
 

 

Recommend
teddy
 
 
题目意思:
一维线性地图
人的位置在n,牛的位置在k
人每走一步有三种选择:+1,-1,*2
问你最少的步数是多少?
 
分析:
很普通的bfs,只有三种操作,如果三种操作后的位置都合法的话,就入队
 
需要注意的地方:
判断是否越界的时候,不能像题目中所说,
当牧场主所在的位置大于10W的时候,就认为他越界。
  因为他有可能先去到
100010的时候 ,在回来。所以再判断的时候,
因为就算了一开始站在10w的位置,你最多跳2倍,也最多到20w
所以
越界的最大值最好为20W。这样就不会出错了。
 
code:
#include<stdio.h>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <cstdlib>
#include <queue>
using namespace std;
#define max_v 100000
int vis[2*max_v+10];
int n,k;
struct node
{
    int x,step;
};
int f(int x)//检查合法性
{
    if(x<0||x>=2*max_v||vis[x]==1)//超出范围或者用过
    {
        return 0;
    }
    return 1;
}
int bfs()
{
    queue<node> q;
    node p,next;

    p.x=n;
    p.step=0;
    vis[n]=1;
    q.push(p);

    while(!q.empty())
    {
        p=q.front();
        q.pop();

        if(p.x==k)
        {
            return p.step;
        }



        //+1,-1,*2 三种情况都加入队列
        next.x=p.x+1;
        if(f(next.x))
        {
            next.step=p.step+1;
            vis[next.x]=1;
            q.push(next);
        }

        next.x=p.x-1;
        if(f(next.x))
        {
            next.step=p.step+1;
            vis[next.x]=1;
            q.push(next);
        }

        next.x=p.x*2;
        if(f(next.x))
        {
            next.step=p.step+1;
            vis[next.x]=1;
            q.push(next);
        }
    }
    return -1;
}
int main()
{
    int ans;
    while(cin>>n>>k)
    {
        memset(vis,0,sizeof(vis));
        ans=bfs();
        cout<<ans<<endl;
    }
    return 0;
}

 

 
posted @ 2018-07-30 17:40  西*风  阅读(423)  评论(0编辑  收藏  举报